Loading an Image object into pygame - image

I'm making a game were you can set the background image yourself.
The selected image is resized to make it fit the purpose, and then i want to load the picture into pygame.
I've something like:
image = Image.open('file')
image.thumbnail(size, Image.ANTIALIAS)
And now I want to load image into pygame.
of course I can use:
image.save(outfile, "JPEG")
background = pygame.image.load('outfile')
Is there a nice way without having to save the image to my hard drive?
Or is it possible that pygame resizes the image?

You can use pygame.transform.scale() to resize an image:
pygame.transform.scale()
resize to new resolution
scale(Surface, (width, height), DestSurface = None) -> Surface
Resizes the Surface to a new resolution. This is a fast scale operation that does not sample the results.
An optional destination surface can be used, rather than have it create a new one. This is quicker if you want to repeatedly scale something. However the destination must be the same size as the (width, height) passed in. Also the destination surface must be the same format.
So you don't have to use PIL.

Related

Keep image centered in resized JavaFX Canvas

I am getting my feet wet with JavaFX, and have a simple drawing program which writes to a Canvas using a PixelWriter. The program draws a pixel at a time, reflecting each pixel over a number of axes to create a growing and evolving pattern centered on the canvas:
The Canvas is in the Center region of a BorderPane, and I have written the code to resize the canvas when the application window is resized. That works OK.
However, I would like to re-center the image on the new resized canvas so that the drawing can continue to grow on the larger canvas. What might be the best approach?
My ideas/attempts so far:
Capture a snapshot of the canvas and write it back to the resized canvas, but that comes out blurry (a couple of code examples below).
I dug into GraphicsContext translations, but that does not seem to move the existing image, just adjusts future drawing.
Maybe instead of resizing the canvas, I make a huge canvas bigger than I would expect my app window to be, and center it over the center region of the border pane (perhaps using a viewport of some kind?) I'm not thrilled about the whole idea of making some arbitrarily huge canvas that I think will be big enough though. I don't want to get into scaling - I am using PixelWriter so that I get the crispest image without antialiasing and other processing.
My snapshot attempt looked like this, but was blurry:
SnapshotParameters params = new SnapshotParameters();
params.setFill(Color.WHITE);
WritableImage image = canvas.snapshot(params, null);
canvas.getGraphicsContext2D().drawImage(image, 50, 50);
The 50, 50 offset above is just for my testing/learning - I'll replace it with a proper computed offset once I get the basic copy working. From the post How to copy contents of one canvas to another? I played with the setFill() parameter, to no effect.
From the post How to save a high DPI snapshot of a JavaFX Canvas I tried the following code. It was more clear, but I have not been able to figure out how to find or compute the pixelScale to get the most accurate snapshot (the value 10 is just some number I typed in bigger than 1 to see how it reacted):
int pixelScale = 10;
WritableImage image = new WritableImage((int)Math.rint(pixelScale * canvas.getWidth()),(int)Math.rint(pixelScale * canvas.getHeight()));
SnapshotParameters params = new SnapshotParameters();
params.setTransform(Transform.scale(pixelScale, pixelScale));
params.setFill(Color.WHITE);
canvas.snapshot(params, image);
canvas.getGraphicsContext2D().drawImage(image, 50, 50);
Thanks for any direction y'all can point me in!

How do I Crop Images in Flutter?

I searching an days for this question.
I want to Crop Images like that, in flutter:
GIF Source: https://github.com/ArthurHub/Android-Image-Cropper
The closest lib for this solution is the Image Lib, that lib offers manipulate images and crop, but i want to crop images in UI level like this gif. All libs I found dont offers that.
There is no widget that performs all that for you. However, I believe that it is possible to write that natively in flutter now. I don't have time at this particular moment to do it for you, but I can definitely point you in the right direction.
You're going to need to load the image in such a way that you can either draw it onto a canvas or use a RawImage to draw it rather than using the Image widget directly.
You need to figure out a co-ordinate system relative to the image
You'll need to find a way of drawing the crop indicator - you could do this either by drawing directly on the canvas or possibly using some combination of GestureDetector/Draggable/DropTarget. I'd suggest that sticking to Canvas might be the easiest to start.
Once the user has selected a part of the image, you need to translate the screen co-ordinates to picture co-ordinates.
You then have to create an off-screen canvas to draw the cropped image to. There are various transforms you'll have to do to makes sure the image ends up in the right place.
Once you've made the off-screen crop, you'll have to display the new image.
All of that is quite a lot of work, and probably a lot of finessing to get right.
Here's examples for a couple of the steps you'll need to do, but you'll have to figure out how to put them together.
Loading an image:
var byteData = await rootBundle.load("assets/image.jpg");
Uint8List lst = new Uint8List.view(byteData.buffer);
var codec = await UI.instantiateImageCodec(lst);
var nextFrame = await codec.getNextFrame();
var image = frameInfo.image;
Displaying an image on a canvas:
https://docs.flutter.io/flutter/dart-ui/Canvas/drawImageRect.html
https://docs.flutter.io/flutter/rendering/CustomPainter-class.html
Writing an image to a off-screen canvas:
ui.Image getCroppedImage(Image image, Rect src, Rect dst) {
var pictureRecorder = new ui.PictureRecorder();
Canvas canvas = new Canvas(pictureRecorder);
canvas.drawImageRect(image, src, dst, Paint());
return pictureRecorder.endRecording().toImage(dst.width.floor(), dst.height.floor());
}
You'll probably need to do something like this answer for getting the local coordinates of mouse/touch gestures.
Some advice - I'd start as simple as possible, not thinking about performance to start (i.e. draw everything each paint if needed, etc). Then once you get the basics working you can start thinking of optimization (i.e. using a RawImage, Transform, and Stack for the image and only re-drawing the selector, etc).
If you need any additional help let me know in a comment and I'll do my best to answer. Now that I've been writing about this a bit it does make me slightly curious to try implementing it so I may try at some point, but it probably won't be soon as I'm quite low on time at the moment. Good luck =D
The image_cropper plugin does exactly what you are looking for.

drawing in Windows memory device context - resolution?

I am trying to export a plot generated by my program in the form of a bitmap. No problem with creating a bitmap in memory (with CreateDIBSection) and saving it on the disk (using GDI+). To draw I have to use device context, and the only one that is easily available is compatible with the screen. So I create a compatible dc, select the bitmap I already created into this device context and I am ready to draw and print into the bitmap. And it works - but it gives me no control over the size of the plot (note: size of the plot, not size of the bitmap). If I understand correctly what is happening mapping modes follow DPI of the screen DC which in turn means size of the plot (and text I put on the plot) is different on different computers.
Is there any way of changing the DPI resolution for the device context? Or perhaps there exist a better way of doing what I am trying to do? Perfect solution would be to ask user for the pixel bitmap size and be able to draw a plot that nicely fits the bitmap.
You don't have to use device context to draw now that you already use Gdiplus over GDI. You just associate your Gdiplus::Graphics object with a Gdiplus::Bitmap instead of HDC. Units and transformations let alone bitmap size are all independent of the device. Hope that helps.
Gdiplus::Bitmap bitmap( L"miranda_kerr.png" ); // draw over existing
Gdiplus::Graphics graphics( &bitmap );
Gdiplus::Pen pen( Gdiplus::Color(255,0,0));
Gdiplus::Status status = graphics.DrawLine( &pen, 20, 20, 100, 500 );
//...

How to read the original alpha channel from PNG in J2ME?

I'm writing a simple J2ME game that uses PNG images with 8-bit alpha channel. Problem: not all hardware supports full alpha transparency rendering. However, since my game is pretty static in nature (at the beginning, "sprites" are layed out onto background image, based on current screen size, and that's about it), I thought it would be possible to prerender those transparent images directly onto background during game initialization and use that later in game. I can't prerender them in Photoshop as their positions are not known in advance.
But, it seems there is no way to read the original alpha channel on devices that do not support semi-transparency as it gets resampled during PNG loading. Is there some library that can help with that? Or is it a good idea to store alpha channels separately (e.g. as separate 8-bit PNG images) and manually apply them?
Thanks!
PNG Images also have transparency support if you want to create transparent image then you have read RGB data along with alpha channels and process alpha
Image transPNG=Image.createImage("/trans.png"); //load the tranparent image
int rgbData[];
transPNG.getRGB(rgbData, 0,transPNG.getWidth(), 0, 0,transPNG.getWidth(), transPNG.getHeight());
Image tranparentImage=Image.createRGBImage(rgbData, width, height, true); //process alpha
transPNG=null;
Above code shows how to create the transparent image and use.
I cant promise this will help, but you can try this way of reading the alpha channel using standard methods from Java util.
BufferedImage image = ImageIO.read(new File(name));
int[] alpha = new int[1]; //containg alpha-value for one pixel.
image.getAlphaRaster().getPixel(x, y, alpha);
System.out.println(alpha[0]); //gives the alpha value for x,y

How to Crop image to the maximum image rect?

In Mac OSX,
I have an image with black pixel in all 4 directions.
I want to programmatically crop the image to the maximum image rect.
Should i check for the black pixel and then create the crop rect or is there any supported API is there?
Create an NSImage of the desired size, lock focus on it, draw the desired crop rectangle of the source image into the whole bounds of the destination image, and unlock focus. The image you created now contains the crop from the source image.
Note that this will lose information like resolution (DPI), color profile, and EXIF tags. If you want to preserve those things (probably a good idea), use CGImage:
Use CGImageSource to load the image. Be sure to recover the properties of each image from the file, as well as the images themselves. And note that I used the plural: TIFF files can contain multiple images.
Use the CGImageCreateWithImageInRect function to crop out the desired section of each image. Don't forget to release each original image as appropriate.
If you want to write the cropped-out images to a file, do so using CGImageDestination. Pass both the images and the attributes dictionaries you obtained in step 1.

Resources