Overlaying images with CImg

半腔热情 提交于 2019-12-11 18:19:04

问题


It seems like this would be very easy, but I am having a lot of problems using the draw_image() function in CImg. Here is a snippet of code:

CImg<unsigned char> landingScreen("desertSunset.bmp"), newGameBTN("newgame.pgm");
CImgDisplay main_disp(landingScreen,"Main Window");
landingScreen.draw_image(400,400,newGameBTN);

I have tried about 8 of the overloaded functions for draw_image(), all to no avail. When I run the program, Main Window pops up with my desertSunset image, but that's it. I am trying to lay newgame.pgm on top of landingScreen, but the image doesn't show up. Is this a problem with depth, or maybe the way I'm structuring the file? I've looked through a bunch of different example files for CImg but they aren't very helpful, and the documentation on these functions is minimal at best. If someone could give a 'Hello World' example of how to draw an image over an image, or tell me what I'm doing wrong, I would greatly appreciate it. Thanks!


回答1:


I created two images like this with ImageMagick:

convert -size 400x300 gradient:red-black PNG24:gradient.png

convert -size 100x100 xc:yellow overlay.png

And then ran this CImg code:

#define cimg_use_png
#define cimg_display 0
#include "CImg.h"
using namespace cimg_library;
int main() {
   CImg<unsigned char> gradient("gradient.png");
   CImg<unsigned char> overlay("overlay.png");
   gradient.draw_image(80,150,overlay);
   gradient.save_png("result.png");
}

And got this:




回答2:


After drawing, you need to refresh your display window as well :

landingScreen.diplay(main_disp);

You choose when the display window is refreshed. It is not done automatically by some running threads.




回答3:


The CImg.draw_image function does not overlay images. It replaces the pixels. There are multiple ways to do image overlay and alpha compositing and they need to be manually implemented (e.g. Multiply, Overlay, ...).

For normal alpha blending, this is how you calculate each pixel:

A = srcA + dstA ( 1 - srcA)
R = (srcR * srcA + dstR * dstA * ( 1 - srcA)) / A
G = (srcG * srcA + dstG * dstA * ( 1 - srcA)) / A
B = (srcB * srcA + dstB * dstA * ( 1 - srcA)) / A



来源:https://stackoverflow.com/questions/16887897/overlaying-images-with-cimg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!