How can I crop an image in Qt? - image

I load a PNG image in a QPixmap/QImage and I want to crop it. Is there a function that does that in Qt, or how should I do it otherwise?

You can use QPixmap::copy:
QRect rect(10, 20, 30, 40);
QPixmap original('image.png');
QPixmap cropped = original.copy(rect);
There is also QImage::copy:
QRect rect(10, 20, 30, 40);
QImage original('image.png');
QImage cropped = original.copy(rect);

Use QImage instead of QPixmap:
QImage image("initial_image.jpg");
QImage copy ;
copy = image.copy( 0, 0, 128, 128);
copy.save("cropped_image.jpg");
This code will save a file cropped to upper left corner 128x128px.

Since you use QPixmap, you can use its copy method and supply it with a QRect to perform the actual crop.

Just use of the QPixmap's copy() functions.
This text is result of reading the first comment on your quiestion:
Sometimes it is better to wrap around an image. That is to have an image that is part of another image or in other words points to a part of another image. This is way the wrapped image does not require additional memory, except for its header. You can display or save the wrapped image without worries. The downside is that the original image must remain valid until you use the wrapped image, also if you are drawing in the wrapped image it will affect the source.

Related

How to add a background image to a button in pygame gui?

I am trying to add an image as a background of a button in pygame gui. I have the button created now and I just need to add the image. How can I add the image to the button?
This is my code
game1 = pygame.Rect(150 , 100, 200, 150) # creates a rect object
pygame.draw.rect(screen, [255, 100, 0], game1) # draw objects down here
it works fine
You're probably looking for pygame.Surface.blit (http://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit)
Load your background image and blit it wherever you want.
img = pygame.image.load('thisisanimage.png')
WhateverYourDisplayNameIs.blit(img,(x,y))
Just in case you're confused, it looks like you're using screen as your display surface.

Is it possible to save a generated image in Codename One?

My question is related to this previous question. What I want to achieve is to stack images (they have transparency), write a string on top, and save the photomontage / photocollage with full resolution.
#Override
protected void beforeMain(Form f) {
Image photoBase = fetchResourceFile().getImage("Voiture_4_3.jpg");
Image watermark = fetchResourceFile().getImage("Watermark.png");
f.setLayout(new LayeredLayout());
final Label drawing = new Label();
f.addComponent(drawing);
// Image mutable dans laquelle on va dessiner (fond blanc)
Image mutableImage = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
drawing.getUnselectedStyle().setBgImage(mutableImage);
drawing.getUnselectedStyle().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);
// Paint all the stuff
paints(mutableImage.getGraphics(), photoBase, watermark, photoBase.getWidth(), photoBase.getHeight());
// Save the collage
Image screenshot = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
f.revalidate();
f.setVisible(true);
drawing.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
err.printStackTrace();
}
}
public void paints(Graphics g, Image background, Image watermark, int width, int height) {
g.drawImage(background, 0, 0);
g.drawImage(watermark, 0, 0);
g.setColor(0xFF0000);
// Upper left corner
g.fillRect(0, 0, 10, 10);
// Lower right corner
g.setColor(0x00FF00);
g.fillRect(width - 10, height - 10, 10, 10);
g.setColor(0xFF0000);
Font f = Font.createTrueTypeFont("Geometos", "Geometos.ttf").derive(220, Font.STYLE_BOLD);
g.setFont(f);
// Draw a string right below the M from Mercedes on the car windscreen (measured in Gimp)
g.drawString("HelloWorld",
(int) (848 ),
(int) (610)
);
}
This is the saved screenshot I get if I use the Iphone6 skin (the payload image is smaller than the original one and is centered). If I use the Xoom skin this is what I get (the payload image is still smaller than the original image but it has moved to the left).
So to sum it all up : why is the saved screenshot with Xoom skin different from the one I get with Iphone skin ? Is there anyway to directly save the graphics on which I paint in the paints method so that the saved image would have the original dimensions ?
Thanks a lot to anyone that could help me :-)!
Cheers,
You can save an image in Codename one using the ImageIO class. Notice that you can draw a container hierarchy into a mutable image using the paintComponent(Graphics) method.
You can do both approaches with draw image on mutable or via layouts. Personally I always prefer layouts as I like the abstraction but I wouldn't say the mutable image approach is right/wrong.
Notice that if you change/repaint a lot then mutable images are slower (this will not be noticeable for regular code or on the simulator) as they are forced to use the software renderer and can't use the GPU fully.
In the previous question it seems you placed the image with a "FIT" style which naturally drew it smaller than the containing container and then drew the image on top of it manually... This is problematic.
One solution is to draw everything manually but then you will need to do the "fit" aspect of drawing yourself. If you use layouts you should position everything based on the layouts including your drawing/text.

Drawing on image and saving

I guess I don't really understand how Graphics objects work in Visual C++ 2010 Express.
I am grabbing a frame from a webcam, and drawing a circle on it. It works great on the screen. I simply create a Graphics object, draw the image, and draw the ellipse.
In the pictureBox_paint function, I have
Graphics^ g = e->Graphics; // from the camera
System::Drawing::Rectangle destRect = System::Drawing::Rectangle(0,0,pbCameraMonitor->Size.Width,pbCameraMonitor->Size.Height);
double slitHeightToWidth = 3;
g->DrawImage(this->currentCamImage,destRect);
int circleX, circleY;
circleX = (int) (pbCameraMonitor->Size.Width - radius/slitHeightToWidth)/2;
circleY = (int) (pbCameraMonitor->Size.Height - radius)/2;
g->DrawEllipse(Pens::Red, circleX, circleY, (int) radius/slitHeightToWidth, (int) radius);
So far so good, my ellipse gets drawn on there nicely. The destRect bit makes sure it is scaled to the pictureBox size. I simply invalidate the pictureBox every time the camera reports a new image, and I have video.
Now, on a button click I want to save this image, with the red ellipse on it. However, I don't want the rescaled version shown on the screen, I want the full res version. So, I'll grab another frame into a Bitmap^ called "grabbedFrame" and do this:
String ^photofile = "Image_" + expRecord.timestamp.ToString("s") + ".jpg"; // get a unique filename
photofile = photofile->Replace(':', '_');
Graphics^ g = Graphics::FromImage(grabbedFrame);
g->DrawEllipse(Pens::Red, 20, 20, 20, 20); // circle size fixed just for demo
grabbedFrame->Save(photofile, System::Drawing::Imaging::ImageFormat::Jpeg);
When I do that, I get a save of the image without the red circle.
Does g->DrawEllipse actually modify the Bitmap? Or just contain the Bitmap + instructions to draw? If the latter, how does the pictureBox know the Bitmap has been modified? If the former, why doesn't my save contain the modification?
How can I save the modified Bitmap?
You need to draw the loaded image into a new Bitmap, make your modifications to that bitmap, and then save it.
Something like (pseudo-code'ish):
// create bitmap and get its graphics
Bitmap^ pBmp = gcnew Bitmap(grabbedFrame->Width, grabbedFrame->Height);
Graphics^ g = Graphics::FromImage(pBmp);
// draw grabbed frame into bitmap
g->DrawImage(grabbedFrame, 0, 0, grabbedFrame->Width, grabbedFrame->Height);
// draw other stuff
g->DrawEllipse(Pens::Red, 20, 20, 20, 20);
// save the result
pBmp->Save(photofile, System::Drawing::Imaging::ImageFormat::Jpeg);

HTML5 canvas - Rescale images on load?

Ok, so I'm doing an html5 canvas game, and I need to draw resized images all the time (it's all pixel-art). Unfortunately, doing the resizing on drawImage makes current browsers quite sluggish, so I'm trying to do the resizing on load, and then just draw the pre-resized image.
I've tried to draw the resized images to a hidden context and then do a ctx.getImageData, but then I'm stuck with a byte array and there's no way to convert to an image. I can do a putImageData to push it to the final context, but that's slow and I apparently lose the alpha channel.
Another option could be to pre-scale things in the server, but I'd like to avoid that if at all possible.
Any ideas?
There is a method on the canvas object (not the context) called toDataURL(string mimeType), this will convert the canvas contents to a base64-encoded binary string of an image. You can use this as the src attribute of any image element.
ctx.drawImage(originalImage, 0, 0, originalImage.width, originalImage.height, 0, 0, 200, 200);
var scaledImage = new Image();
scaledImage.onload = ...;
scaledImage.src = canvas.toDataURL("image/png");
Now you can draw your scaled image normaly.

ImageList Transparency on Listviews?

EDIT: I've offered a bounty, since I doubt I'll be getting any answers otherwise.
Lately I've been working with listviews and I've decided to add an icon for each item indicating whether it's input or output. The icons add fine, but they're not transparent:
As can be seen, the icons are clearly not transparent. I'm currently doing something like this load the icons:
hImageList = ImageList_Create(16, 16, ILC_MASK | ILC_COLOR32, 2, 2);
if (hImageList != NULL)
{
iIN = ImageList_AddIcon(hImageList, LoadIcon(hInstance, MAKEINTRESOURCE(101)));
iOUT = ImageList_AddIcon(hImageList, LoadIcon(hInstance, MAKEINTRESOURCE(102)));
}
I've tried messing with the flags for ImageList_Create & LoadIcon/LoadImage but have had no luck and to be honest I've run out of ideas.
Any help would be very appreciated.
First up, ImageList_ReplaceIcon copies the icon data when adding it to an image list. So the HICON needs to be released afterwards.
Next, imagelists are natively bitmaps, not icons. And the way you are creating your imagelist makes the conversion of icon to bitmap very ambiguous. ILC_COLOR32 implies the imagelist should be created as a 32bit dib section, which typically contain transparency information via an embedded alpha channel. ILC_MASK instead implies that the internal bitmaps are DDB bitmaps, with the transparency information stored as a 1bpp mask bitmap.
The quickest solution to your problem - take your two icons:
Merge them into a single bitmap resource thats 32 pels wide by 16 high. Fill the background with a mask color :- purple or something.
Create the bitmap using ILC_COLOR|ILC_MASK
Load the bitmap being sure NOT to use LR_TRANSPARENT.
Add the bitmap using ImageList_AddMasked passing in a COLORREF that represents the mask color.
OR, for a better visual effect...
export your PNG data as a 32x16 32bpp bitmap file containing pre-multiplied alpha channel data.
Create the imagelist using the ILC_COLOR32 value.
LoadImage() with LR_CREATEDIBSECTION to load the bitmap as a 32bpp dib section.
Add the image using ImageList_Add()
(the last option is kind of tricky as the number of tools that support writing out 32bit bmp files with properly pre multiplied alpha channels is rather low).
Edited to add the following code sample. Using a 4bpp bitmap created in the dev environment this works just great :-
HWND hwndCtl = CreateWindowEx(0,WC_LISTVIEW,TEXT("ListView1"),WS_CHILD|WS_VISIBLE|WS_HSCROLL|WS_VSCROLL,0,0,cx,cy,hWnd,(HMENU)101,hModule,NULL);
HBITMAP hbm = (HBITMAP)LoadImage(hModule,MAKEINTRESOURCE(IDB_BITMAP1),IMAGE_BITMAP,0,0,0);
COLORREF crMask=RGB(255,0,255);
HIMAGELIST himl = ImageList_Create(16,16,ILC_COLOR|ILC_MASK,2,0);
ImageList_AddMasked(himl,hbm,crMask);
ListView_SetImageList(hwndCtl,himl,LVSIL_NORMAL);
You want to make your icons have a background color that isn't used anywhere else in the icon, like a really ugly purple, and then use LoadImage(..., LR_LOADTRANSPARENT); The flag says look at the first pixel at 0,0 and make everything that color transparent.
Your code looks fine to me, I always use LoadImage instead of LoadIcon but I suspect that doesn't matter. Have you checked that the icons do indeed have transparent areas and don't themselves have a solid background?
My LoadImage calls look like:
HICON hIcon = (HICON)LoadImage(hinstResources,MAKEINTRESOURCE(IDI_ICON),IMAGE_ICON,16,16,LR_DEFAULTCOLOR);
Here... Create an ImageList, as suggested, make your icons into a Bitmap, 16 pixels high, by 16*n long, where n= the number of icons...
Set the background color to 255, 0, 255, like you have done.
Then, load it, and add it to the image list as I did here:
m_ImageList.Create(16, 16, ILC_COLOR16 | ILC_MASK, 7, 1);
CBitmap bm;
bm.LoadBitmap(IDB_SUPERTREEICONS);
m_ImageList.Add(&bm, RGB(255, 0, 255));
GetTreeCtrl().SetImageList(&m_ImageList, TVSIL_NORMAL);
Of course, this was written in MFC, but as you know, it's just a wrapper to Win32...
Outside of this, you are going to have to go to a custom draw control, in which you draw the icon over whatever background the icon happens to be sitting on. There isn't really any magic "transparent" color, that I know of, in any of these controls.
In the case of a custom draw, you need to use code like the following:
#define TRANSPARENT_COLOR (255,0,255)
UINT iBitmap = IDB_ICON_UP
CDC *dc = GetDC();
int x = 0, y = 0;
CDC *pDisplayMemDC = new CDC;
CDC *pMaskDC = new CDC;
CDC *pMemDC = new CDC;
CBitmap *pBitmap = new CBitmap;
CBitmap *pMaskBitmap = new CBitmap;
CBitmap *pMemBitmap = new CBitmap;
int cxLogo, cyLogo;
BITMAP bm;
pBitmap->LoadBitmap(iBitmap);
pDisplayMemDC->CreateCompatibleDC(dc);
CBitmap *pOldBitmap = (CBitmap *)pDisplayMemDC->SelectObject(pBitmap);
pBitmap->GetObject(sizeof(bm), &bm);
cxLogo = bm.bmWidth;
cyLogo = bm.bmHeight;
pMaskBitmap->CreateBitmap(cxLogo, cyLogo, 1, 1, NULL);
pMaskDC->CreateCompatibleDC(dc);
CBitmap *pOldMask = (CBitmap *)pMaskDC->SelectObject(pMaskBitmap);
COLORREF oldBkColor = pDisplayMemDC->SetBkColor(TRANSPARENT_COLOR);
pMaskDC->BitBlt(0, 0, cxLogo, cyLogo, pDisplayMemDC, 0, 0, SRCCOPY);
pMemBitmap->CreateCompatibleBitmap(dc, cxLogo, cyLogo);
pMemDC->CreateCompatibleDC(dc);
CBitmap *pOldMem = (CBitmap *)pMemDC->SelectObject(pMemBitmap);
pMemDC->BitBlt(0, 0, cxLogo, cyLogo, dc, x, y, SRCCOPY);
pMemDC->BitBlt(0, 0, cxLogo, cyLogo, pDisplayMemDC, 0, 0, SRCINVERT);
pMemDC->BitBlt(0, 0, cxLogo, cyLogo, pMaskDC, 0, 0, SRCAND);
pMemDC->BitBlt(0, 0, cxLogo, cyLogo, pDisplayMemDC, 0, 0, SRCINVERT);
dc->BitBlt(x, y, cxLogo, cyLogo, pMemDC, 0, 0, SRCCOPY);
delete pMemDC->SelectObject(pOldMem);
delete pMemDC;
delete pMaskDC->SelectObject(pOldMask);
delete pMaskDC;
delete pDisplayMemDC->SelectObject(pOldBitmap);
delete pDisplayMemDC;
This code decides where to draw the icon, and takes a snapshot of the background, creates a mask for the icon, and then draws it over the background, giving it a fully transparent background...
Hope that helps somewhat. If not, please explain in more detail what you are trying to make happen, and what you are seeing, or what you are NOT seeing...
I struggled with the same issue using an ImageList in a Tree View. I eventually got Chris Becke's second solution to work, creating an ImageList using the ILC_COLOR32 flag and using LoadImage() with the LR_CREATEDIBSECTION flag. This solution, and probably also the first solution, requires what is described below.
Transparency (and themes) are only supported with comctl32.dll version 6+, to use the correct version, the pre-processor directive on this page worked for me:
https://learn.microsoft.com/en-us/windows/win32/controls/cookbook-overview

Resources