0

I am working on a project that involves pattern detection. I have to scale the input images to a specific size and test for pixel colour.

I tried to take in a java.awt.Image so I could resize it, then convert it to BufferedImage to test for the RGB value for each independent pixel. However, casting BufferedImage to Image does not work.

Since java.awt.Image cannot access the color value of each individual pixel, I have to use the .getRBG functions of a BufferedImage. However, I have to take in a java.awt.Image because BufferedImage cannot be resized. I did some research about resizing the BufferedImage but all the result I found is about resizing it on screen, but not the actual image. I am NOT trying to display the BufferedImage on screen, I am trying to access the colour value of each pixel on an image.

These are the ways that could fix my issue: Please suggest a way to...

  • Scale a BufferedImage (that doesn't involve drawing on the screen, just resizing the BufferedImage itself)

or

  • Access the colour value of a pixel in java.awt.Image
Image img = ImageIO.read(inputFile).getScaledInstance(400, 400, 0);

BufferedImage scaledImage = (BufferedImage)img;

The following code does not compile because BufferedImage cannot be cast to java.awt.Image

Alan Sun
  • 1
  • 1

1 Answers1

0
String imagePath = "path/to/your/image.jpg";
BufferedImage myPicture = ImageIO.read(new File(imagePath));

You can use ImageIO, check this documentation: Converting Image to BufferedImage

Or this amazing tutorial: https://www.baeldung.com/java-images Or even this same question in 2012: Converting Image to BufferedImage

If I answer wrong your question, let me know.

For resize your image, you can try use something like that:

public static BufferedImage resize(BufferedImage img, int newW, int newH) { 
    Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();

    return dimg;
}  

this answer come from: Bufferedimage resize

Matheus Mello
  • 310
  • 2
  • 5
  • I already read the image into a java.awt.Image variable. I need to convert this image that is already read to a BufferedImage so I can access each individual pixels. Or I just need a way to resize the BufferedImage file. – Alan Sun May 30 '19 at 01:10