7

How do I save a file with transparency to a JPEG file without Qt making the transparent color black? I know JPEG doesn't support alpha, and the black is probably just a default "0" value for alpha, but black is a horrible default color.

It seems like this should be a simple operation, but all of the mask and alpha functions I've tried are ignored when saving as JPEG.

For example:

image->load("someFile.png"); // Has transparent background or alpha channel
image->save("somefile.jpg", "JPG"); // Transparent color is black

I've tried filling the image with white before saving as a JPEG, converting the image to ARGB32 (with 8-bit alpha channel) before saving, and even tried ridiculously slow stuff like:

QImage image2 = image1->convertToFormat(QImage::Format_ARGB32);
image2.setAlphaChannel(image1->alphaChannel());
image2.save(fileURI, "JPG", this->jpgQuality; // Still black!


See: http://67.207.149.83/qt_black_transparent.png for a visual.
Charles Burns
  • 10,310
  • 7
  • 64
  • 81

3 Answers3

11

I'd try something like this (i.e., load the image, create another image of the same size, paint the background, paint the image):

QImage image1("someFile.png"); 
QImage image2(image1.size());
image2.fill(QColor(Qt::white).rgb());
QPainter painter(&image2);
painter.drawImage(0, 0, image1);
image2.save("somefile.jpg", "JPG");
Lukáš Lalinský
  • 40,587
  • 6
  • 104
  • 126
  • This code got me on the right track. Your idea of using the QPainter to paint the incoming image over a manually draw white background worked. You have my thanks. I wish there were a faster way to do this, but for now I am content that it works at all. – Charles Burns Oct 12 '09 at 06:16
  • Well, the fastest way is probably doing it yourself. You can use `bits()` to get the raw data, iterate over it, check if `qAlpha()` of a pixal is below 255, blend the color with white. – Lukáš Lalinský Oct 12 '09 at 06:38
  • I don't know what version of Qt this code was using back then (4.5, 4.6?) but now 5 years later (!) in Qt 4.8 and Qt 5.x, the constructor of QImage taking a QSize [requires to pass a Format as well](http://qt-project.org/doc/qt-4.8/qimage.html#QImage-2). There is a new fill method that [takes a Qt::Global color](http://qt-project.org/doc/qt-4.8/qimage.html#fill-2) as well. – Uflex Jan 16 '14 at 15:01
-2

Jpeg doesn't support transparency

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
-2

True if you want to use Alpha Chanel (Transparent) you should save the imge in *.png *.bmp formats

Andres
  • 1
  • 2
    Please read the question completely -- I mention that I am aware that JPG does not support transparency in the second sentence. Neither does *.bmp, by the way. The problem was that, when saving to JPEG *from* an image with transparency, the transparent values are interpreted as black. – Charles Burns Jul 04 '10 at 06:10