Reputation: 33
Is it possible to edit a image in java? I mean to draw a pixel in a certain RGB color in a certain spot and save the image.
I'm working on a game where the objects are loaded by an image and in order to save the current state of the map I need to edit some pixels and load it later.
Any help is appreciated! :)
Upvotes: 2
Views: 1053
Reputation: 39
It is. If you create an instance of BufferedImage, which is an object that stores image data, you will be able to get the pixels and change them. Here is how:
public static void main(String[] args) throws Exception {
BufferedImage originalImage = ImageIO.read(inputFile);
BufferedImage newImage = orgiginalImage;
int[] pixels = ((DataBufferInt)newImage.getRaster().getDataBuffer()).getData();
for(int i = 0; i < pixels.length; i++){
// Code for changing pixel data;
pixels[i] = 0xFFFFFFFF // White
// Syntax for setting pixel color: 0x(HEX COLOR CODE)
// There is no need to set these pixels to the image; they are allerady linked
// For instance, if you create a Canvas object in a JFrame,
// and used graphics.drawImage(newImage, 0, 0,
// newImage.getWidth(), newImage.getHeight(), null), it will be up to date
// Another example is, if you saved newImage to a file, it willallready have
// the white pixels drawn in.
}
}
Upvotes: 1