如何翻转QImage

时间:2015-02-09 11:58:07

标签: c++ qt5 transformation qimage

翻转/镜像QImage的正确方法是什么?以下代码段不起作用。

 //allocate buffer
 BYTE* pRgb32Buffer = new BYTE[width*height* 4];
 //create paint device
 QImage img = QImage(pRgb32Buffer , width, height, getStride(width, pixelFormat), QImage::Format_RGB32);
 //do some drawing on image (works!) 
 QPainter painter(&img);
 painter.drawText(10, 50, QString("some text"));
 //mirrore image (doesn't mirror the orignal buffer!!!)
 img = img.mirrored(false,true);
 //doesn't work either
 //QImage mirrored = img.mirrored();
 //img = mirrored;
 //mirrored.detach(); 

2 个答案:

答案 0 :(得分:2)

使用QImage::mirrored()的解决方案:

memmove(pRgb32Buffer, img.mirrored().bits(),img.byteCount());

答案 1 :(得分:2)

我有这个工作代码将QPixmap镜像到QImage上。

QPixmap* source = //... Getting my pixmap form somewhere...
QImage target(QSize(source->width(), source->height()), QImage::Format_ARGB32);
QPainter painter(&target);
QTransform transf = painter.transform();
transf.scale(-1, 1);
painter.setTransform(transf);
painter.drawPixmap(-source->width(), 0, *source);

source包含该代码后的镜像像素图。您应该可以使用QImageQPainter::drawImage功能作为替代方案。

如果需要,您可以选择保存文件(确保您拥有图像格式dll或者它不会写入):

QImageWriter writer("c:\\theimage.tiff", "tiff");
writer.setCompression(1);
writer.write(target);