QImageRGB32到QImageRGB24,某种图像的不良结果

QImage RGB32 to QImage RGB24, bad result with some kind of image

本文关键字:图像 不良 结果 QImageRGB24 QImageRGB32      更新时间:2023-10-16

我尝试将带有RGB32的QImage转换为带有RGB24的QImage。我的代码在这种情况下不起作用:

当图像的BMP标头中有额外的1024个字节时,图像的大小为X*Y*3+54+1024个未知字节。

奇怪的是,如果图像分辨率x==分辨率y,例如:512x512或1024x1024,代码就会工作。无论情况如何:当我在标头中有或没有额外的1024字节时

如果BMP的头中没有额外的1024字节,即使分辨率x不同于分辨率y,一切都很好。我的代码:

QImage * img=new QImage("test.jpg");//load img as RGB32 32bit per pixel whatever the format of input
QImage * tmp_img=new QImage(img->width(),img->height(),QImage::Format_RGB888);// image dest 24bit per pixel
     uchar * ptr1=img->bits();
     uchar * ptr2=tmp_img->bits();
     for( int k1=0,k2=0;k1<img->width()*img->height()*4;k1+=4,k2+=3)//increment k1 by 4 because img format is RGB32
                                                  //increment k2 by 3 because tmp_img format is RGB888
     {
         ptr2[k2]=ptr1[k1];
         ptr2[k2+1]=ptr1[k1+1];
         ptr2[k2+2]=ptr1[k1];
     }

删除了旧答案。

为什么不简单地这样做:

QImage img2 = img->convertToFormat(QImage::Format_RGB888);