Due to lack of tutorials and books that are, like, readable I started experimanting with manipulating image data (raster). This is the thread where I’ll ask questions until I get the image manipulation
I have some questions… am I doing it right? I load BufferedImage, take it’s raster, create a compatibile writable raster, change it, create new BuffferedImage using changed raster.
The thing is, in compilable code below (you need “images/player.png” to make it work) it’s all fine if I create new image with original raster (a duplicate image for testing if it works), but if I createCompatibleWritableRaster() and use that raster, new image dosen’t appear. What’s wrong? Also I use BufferedImage constructor that takes width, height and type… and for some reason original_image.getType() return custom type (int 0) … I need to manually enter BufferedImage.TYPE_INT_ARGB (int 12) to make it work, otherwise constructor throws exception and complain it can’t use 0.
Thank you all.
Copied image dosen’t show here:
import java.awt.*;
import java.awt.image.*;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Test extends JFrame {
private BufferedImage original_image;
private BufferedImage copy_image;
public static void main(String[] args) {
Test frame = new Test();
}
public Test() {
super("Image processing Test");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(0, 0, 400, 300);
this.setLocation(300,250);
original_image = loadImage("images/player.png"); // uses ImageIO.read()
int imgHeight = original_image.getHeight();
int imgWidth = original_image.getWidth();
Raster org_raster = original_image.getData();
copy_image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
WritableRaster mod_raster = org_raster.createCompatibleWritableRaster();
// for (int i=0; i<40; i++) {
// mod_raster.setPixel(i,0, new int[] {255,0,0,0});
// }
copy_image.setData(mod_raster);
this.setVisible(true);
}
public BufferedImage loadImage(String path) {
URL url = null;
try {
url = Test.class.getClassLoader().getResource(path);
return ImageIO.read(url);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error loading image: " + path + " " + url);
System.exit(0);
return null;
}
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.clearRect(0, 0, getWidth(), getHeight());
g2d.drawImage(original_image, 50, 50, null);
g2d.drawImage(copy_image, 50, 100, null);
g2d.dispose();
}
}