Wednesday, 16 January 2013

Loading and Saving Images


Loading and Saving Images

Instead of using graphics primitives, you can use photos and other
graphical material in the JPEG or PNG formats. The handling of these
materials is done through the Image object in a similar way to the way
graphics primitives are handled. Note that once a pre-made image has
been loaded, you can use it in the same way as any other Image object,
for example, any of the above graphic primitives can be drawn on it.
A pre-made image is loaded and saved to a new file as follows:
img = graphics.Image.open("e:\\Images\\picture.jpg")
img.save("e:\\Images\\picture_new.jpg")

 Image Masks

When you copy one image to another using the blit() function, the
shape of the source image is rectangular by default. In some cases, this is
not desirable and you would like to mask out certain parts of the source
image.
For this purpose, you need a black and white mask image with the
visible parts painted in white. Figure 5.5 shows an example: on the left,
there is the original image and, on the right, the corresponding mask that
masks out the background of the arrow.

Then, you can load and use the mask to copy only the visible parts,
defined by the mask, mask img, of the source image, src img, to the
canvas as follows:

mask_img = Image.new(size = (50, 50), mode = '1')
mask_img.load('e:\\Images\\mask_img.png')
src_img = graphics.Image.open('e:\\Images\\orig_img.png')
canvas.blit(src_img, target=(0,0), source=(0,0), mask = mask_img)

The parameter mode = "1" specifies that the new image, mask img,
has only two colors, black and white. This mode is required for masks.
Section 11.5 presents an example that uses masks extensively.


No comments:

Post a Comment