Answer the question
In order to leave comments, you need to log in
How to fix byte alignment issue when loading image with libjpeg?
I have a 259x194 image. Loading it with libjpeg starts the "fun".
The image is shifted by about half.
void JPEGTexture::genData()
{
FILE *f=fopen(filepath.c_str(),"rb");
if (f==NULL) return;
struct jpeg_error_mgr jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, f);
jpeg_read_header(&cinfo, TRUE);
imageWidth = cinfo.image_width;
imageHeight = cinfo.image_height;
initTextureSize();
std::vector<unsigned char> buf(3*imageWidth*imageHeight);
jpeg_start_decompress(&cinfo);
for (int y=0;y<imageHeight;y++) {
JSAMPLE *rows[1];
rows[0]=&buf[3*imageWidth*(imageHeight-1-y)];
jpeg_read_scanlines(&cinfo,rows,1);
}
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, getTextureWidth(), getTextureHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, getImageWidth(), getImageHeight(),GL_RGB, GL_UNSIGNED_BYTE, &buf[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
this->textureID=texture;
jpeg_destroy_decompress(&cinfo);
fclose(f);
}
Answer the question
In order to leave comments, you need to log in
We'll have to ask a few clarifying questions:
0) is libjpeg necessary? If you want to load textures, FreeImage is perfect, it is certainly thicker by definition, but it is much easier with it, and you can switch the format, if that.
1) are you sure the problem is how the texture is loaded and not how you draw? If you fill it with a solid color in the shader, does everything render normally?
2) Is there a problem with flowers? Do the color formats match exactly?
3) how do you solve the problem with the fact that the size of the picture is not a power of two?
4) getTextureWidth(), getTextureHeight() - what do these calls do? What size is the texture?
Images must be aligned on a 4-byte boundary.
std::vector<unsigned char> buf(3*imageWidth*imageHeight);
...
rows[0]=&buf[3*imageWidth*(imageHeight-1-y)];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question