- Opening an image
- 4 Answers 4
- Reading/Loading an Image
- How do I make java’s ImageBuffer to read a PNG file correctly?
- How do I read pixels from a PNG file?
- 5 Answers 5
- Screensot
- Full code
- How to read PNG files in Java
- What is a PNG?
- How to read a PNG image in Java with ImageIO
- How to read a PNG image in Java with JDeli
- Download your JDeli guide:
- Start reading and writing images with one line of code
Opening an image
And the file is in the src folder for sure. But it throws the exception everytime even though the file is there, no misspellings. edit: The first sentence was true, I didn’t put the image in the root.
What exception does it throw? Also the src folder doesn’t mean that it’s going to be found.. it needs to be in the runtime folder. How are you running it?
The image file should go into the root of your eclipse project, not in the src/ folder. Also please post the stacktrace
4 Answers 4
Been there as well, know that feeling. Anyway, try print out current working directory and that will tell you exactly where is the application really read from.
Relevant reference: java.io.file docs Also, using absolute path (like /home/Stuff/Pictures/picture.png ) worth a shot. In other hand , it’s OS dependent. Note: File object has an getParent() method, which, in this case, might do the same.
Okay, that’s a very constructive comment and that’s positive. Lately, no idea why SO deducted user reputation without giving good reason. Lost my faith toward SO to actively contribute in the future.
Try to specify the path of your image. For example:
Image picture = ImageIO.read(new File("C:/Desktop/picture.png"));
Or if the image is in your workspace, for example:
Image picture = ImageIO.read(new File("C:/workspace/Project/src/picture.png"));
You can see the image location (the path of your image) clicking with the right button of the mouse in the image, then Properties.
You can use one slah ( / ) or two backslashs ( \\ ) to separate the directories of the path.
There is a dichotomy in java.
- If your file is part of the deliverable project, a file which can be packed in the application jar file, then it is a resource.
Image picture = ImageIO.read(SomeClassOfYours.class.getResource("/picture.png"));
The path is relative to that class, and can be made an absolute path. All on the java class path of the application.
- If your file is a file system file, a File , then the path best is a full absolute path. A relative path depends at which working directory the application is run, and that might differ.
Image picture = ImageIO.read(new File("C:/. /src/picture.png"));
The question seems to indicate that the image is a read-only part of the application, in which case it is a resource file. The path must be case sensitive, and the path separator must be a forward slash / .
Reading/Loading an Image
When you think of digital images, you probably think of sampled image formats such as the JPEG image format used in digital photography, or GIF images commonly used on web pages. All programs that can use these images must first convert them from that external format into an internal format.
Java 2D supports loading these external image formats into its BufferedImage format using its Image I/O API which is in the javax.imageio package. Image I/O has built-in support for GIF, PNG, JPEG, BMP, and WBMP. Image I/O is also extensible so that developers or administrators can «plug-in» support for additional formats. For example, plug-ins for TIFF and JPEG 2000 are separately available.
To load an image from a specific file use the following code, which is from LoadImageApp.java :
BufferedImage img = null; try < img = ImageIO.read(new File("strawberry.jpg")); >catch (IOException e)
Image I/O recognises the contents of the file as a JPEG format image, and decodes it into a BufferedImage which can be directly used by Java 2D.
LoadImageApp.java shows how to display this image.
If the code is running in an applet, then its just as easy to obtain the image from the applet codebase. The following excerpt is from LoadImageApplet.java :
The getCodeBase method used in this example returns the URL of the directory containing this applet when the applet is deployed on a web server. If the applet is deployed locally, getCodeBase returns null and the applet will not run.
The following example shows how to use the getCodeBase method to load the strawberry.jpg file.
Note: If you don’t see the applet running, you need to install at least the Java SE Development Kit (JDK) 7 release.
LoadImageApplet.java contains the complete code for this example and this applet requires the strawberry.jpg image file.
In addition to reading from files or URLS, Image I/O can read from other sources, such as an InputStream. ImageIO.read() is the most straightforward convenience API for most applications, but the javax.imageio.ImageIO class provides many more static methods for more advanced usages of the Image I/O API. The collection of methods on this class represent just a subset of the rich set of APIs for discovering information about the images and for controlling the image decoding (reading) process.
We will explore some of the other capabilities of Image I/O later in the Writing/Saving an Image section.
How do I make java’s ImageBuffer to read a PNG file correctly?
For some reason, opening up some PNG files using ImageBuffer and ImageIO does not work. Here’s some code I am using that works fine for resizing/cropping JPGs:
BufferedImage image = ImageIO.read(new File(location)); BufferedImage croppedImage = image.getSubimage( cropInfo.getX(), cropInfo.getY(), cropInfo.getW(), cropInfo.getH()); BufferedImage resizedImage = new BufferedImage( TARGET_WIDTH, TARGET_HEIGHT, croppedImage.getType()); Graphics2D g = resizedImage.createGraphics(); g.drawImage(croppedImage, 0, 0, TARGET_WIDTH, TARGET_HEIGHT, null); g.dispose(); this.changeContentType("image/png", ".png"); // not really relevant. just a property ImageIO.write(resizedImage, "png", new File(location)); return resizedImage;
The goal of this function is to take whatever type is given, resize and crop the image, and then save it to PNG with the same filename. It works on Windows, but if I crop/resize on Linux (lenny), it crashes altogether and complains about the type of the file (it says the type is 0).
java.lang.IllegalArgumentException: Unknown image type 0 java.awt.image.BufferedImage.(BufferedImage.java:490) trainingdividend.domain.file.ServerImage.resizeImage(ServerImage.java:68) trainingdividend.domain.file.ServerImage.cropAndResize(ServerImage.java:80) trainingdividend.service.user.UserAccountManagerImpl.cropAvatar(UserAccountManagerImpl.java:155) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
How do I read pixels from a PNG file?
I know how to capture a screenshot by using Robot, Windowtester or FEST. I also know how to read a pixel from the screen by using robot.
int x = 10; int y = 10; Color px = getPixelColor(int x, int y);
However, I don’t know how to read a pixel from an image that is already captured. I’m planning to compare a current image, with an image from file. Lets say both are PNG. Are there any frameworks that I can use to compare images pixel by pixel?
5 Answers 5
Is this in Java? If so, you can use ImageIO.read( «yourImage.png» ) to get a BufferedImage . That will have a getData() method which will give you a Raster object, on which you can call getPixel . See link
javax.imageio.ImageIO.read(new File("filename.png"))
Then you can walk through the pixels and compare with the images pixel by pixel with this:
java.awt.image.BufferedImage.getRGB(int x, int y).
And then get color using getRGB method.
Load them as BufferedImage instances and it is relatively easy.
Here is part of code that creates images with text, then creates a new image that shows the difference between the image with & without text.
for (int xx=0; xx bnwImage.setRGB(xx, yy, bnw.getRGB()); int rD = Math.abs(r1-r2); int gD = Math.abs(g1-g2); int bD = Math.abs(b1-b2); Color differenceColor = new Color(rD,gD,bD); differenceImage.setRGB(xx, yy, differenceColor.getRGB()); > >
Screensot
Full code
import java.awt.image.BufferedImage; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.imageio.*; import java.io.*; import javax.imageio.stream.ImageOutputStream; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import java.util.Locale; class ImageWriteTest < private BufferedImage originalImage; private BufferedImage textImage; private BufferedImage differenceImage; private BufferedImage bnwImage; private JPanel gui; private JCheckBox antialiasing; private JCheckBox rendering; private JCheckBox fractionalMetrics; private JCheckBox strokeControl; private JCheckBox colorRendering; private JCheckBox dithering; private JComboBox textAntialiasing; private JComboBox textLcdContrast; private JLabel label0_1; private JLabel label0_4; private JLabel label0_7; private JLabel label1_0; private JTextArea output; final static Object[] VALUES_TEXT_ANTIALIASING = < RenderingHints.VALUE_TEXT_ANTIALIAS_OFF, RenderingHints.VALUE_TEXT_ANTIALIAS_ON, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB >; final static Object[] VALUES_TEXT_LCD_CONTRAST = < new Integer(100), new Integer(150), new Integer(200), new Integer(250) >; ImageWriteTest() < int width = 280; int height = 100; gui = new JPanel(new BorderLayout(0,4)); originalImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); textImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); differenceImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); bnwImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); JPanel controls = new JPanel(new GridLayout(0,2,0,0)); antialiasing = new JCheckBox("Anti-aliasing", false); rendering = new JCheckBox("Rendering - Quality", true); fractionalMetrics = new JCheckBox("Fractional Metrics", true); strokeControl = new JCheckBox("Stroke Control - Pure", false); colorRendering = new JCheckBox("Color Rendering - Quality", true); dithering = new JCheckBox("Dithering", false); controls.add(antialiasing); controls.add(rendering); controls.add(fractionalMetrics); controls.add(colorRendering); textLcdContrast = new JComboBox(VALUES_TEXT_LCD_CONTRAST); JPanel lcdContrastPanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); lcdContrastPanel.add(textLcdContrast); lcdContrastPanel.add(new JLabel("Text LCD Contrast")); controls.add(lcdContrastPanel); controls.add(strokeControl); textAntialiasing = new JComboBox(VALUES_TEXT_ANTIALIASING); controls.add(textAntialiasing); controls.add(dithering); ItemListener itemListener = new ItemListener()< public void itemStateChanged(ItemEvent e) < updateImages(); >>; antialiasing.addItemListener(itemListener); rendering.addItemListener(itemListener); fractionalMetrics.addItemListener(itemListener); strokeControl.addItemListener(itemListener); colorRendering.addItemListener(itemListener); dithering.addItemListener(itemListener); textAntialiasing.addItemListener(itemListener); textLcdContrast.addItemListener(itemListener); Graphics2D g2d = originalImage.createGraphics(); GradientPaint gp = new GradientPaint( 0f, 0f, Color.red, (float)width, (float)height, Color.orange); g2d.setPaint(gp); g2d.fillRect(0,0, width, height); g2d.setColor(Color.blue); for (int ii=0; ii g2d.setColor(Color.green); for (int jj=0; jj updateImages(); gui.add(controls, BorderLayout.NORTH); JPanel images = new JPanel(new GridLayout(0,2,0,0)); images.add(new JLabel(new ImageIcon(originalImage))); images.add(new JLabel(new ImageIcon(textImage))); images.add(new JLabel(new ImageIcon(differenceImage))); images.add(new JLabel(new ImageIcon(bnwImage))); try < label0_1 = new JLabel(new ImageIcon(getJpegCompressedImage(0.1f, textImage))); images.add(label0_1); label0_4 = new JLabel(new ImageIcon(getJpegCompressedImage(0.4f, textImage))); images.add(label0_4); label0_7 = new JLabel(new ImageIcon(getJpegCompressedImage(0.7f, textImage))); images.add(label0_7); label1_0 = new JLabel(new ImageIcon(getJpegCompressedImage(1.0f, textImage))); images.add(label1_0); >catch(IOException ioe) < >gui.add(images, BorderLayout.CENTER); StringBuilder sb = new StringBuilder(); String[] names = < "java.vendor", "java.version", "java.vm.version", "os.name", "os.version" >; for (String name : names) < addProperty(sb, name); >output = new JTextArea(sb.toString(),6,40); gui.add(new JScrollPane(output), BorderLayout.SOUTH); JOptionPane.showMessageDialog(null, gui); > private static void addProperty(StringBuilder builder, String name) < builder.append( name + " \t" + System.getProperty(name) + "\n" ); >/** Adapted from SO post by x4u. */ private Image getJpegCompressedImage(float quality, BufferedImage image) throws IOException < ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ImageWriter imgWriter = ImageIO.getImageWritersByFormatName( "jpg" ).next(); ImageOutputStream ioStream = ImageIO.createImageOutputStream( outStream ); imgWriter.setOutput( ioStream ); JPEGImageWriteParam jpegParams = new JPEGImageWriteParam( Locale.getDefault() ); jpegParams.setCompressionMode( ImageWriteParam.MODE_EXPLICIT ); jpegParams.setCompressionQuality( quality ); imgWriter.write( null, new IIOImage( image, null, null ), jpegParams ); ioStream.flush(); ioStream.close(); imgWriter.dispose(); BufferedImage compressedImage = ImageIO.read(new ByteArrayInputStream(outStream.toByteArray())); JLabel label = new JLabel("Quality: " + quality); label.setBackground(new Color(255,255,255,192)); label.setOpaque(true); label.setSize(label.getPreferredSize()); label.paint(compressedImage.getGraphics()); return compressedImage; >private void updateImages() < int width = originalImage.getWidth(); int height = originalImage.getHeight(); Graphics2D g2dText = textImage.createGraphics(); if (antialiasing.isSelected()) < g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); >else < g2dText.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); >if (rendering.isSelected()) < g2dText.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); >else < g2dText.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); >if (fractionalMetrics.isSelected()) < g2dText.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); >else < g2dText.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF); >if (strokeControl.isSelected()) < g2dText.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); >else < g2dText.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); >if (dithering.isSelected()) < g2dText.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); >else < g2dText.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); >if (colorRendering.isSelected()) < g2dText.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); >else < g2dText.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); >g2dText.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, textLcdContrast.getSelectedItem()); g2dText.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, textAntialiasing.getSelectedItem()); g2dText.drawImage(originalImage, 0,0, null); g2dText.setColor(Color.black); g2dText.drawString("The quick brown fox jumped over the lazy dog.", 10,50); Graphics2D g2dDifference = differenceImage.createGraphics(); Graphics2D g2dBnW = bnwImage.createGraphics(); for (int xx=0; xx bnwImage.setRGB(xx, yy, bnw.getRGB()); int rD = Math.abs(r1-r2); int gD = Math.abs(g1-g2); int bD = Math.abs(b1-b2); Color differenceColor = new Color(rD,gD,bD); differenceImage.setRGB(xx, yy, differenceColor.getRGB()); > > gui.repaint(); > public static void main(String[] args) < SwingUtilities.invokeLater( new Runnable() < public void run() < ImageWriteTest iwt = new ImageWriteTest(); >> ); > >
How to read PNG files in Java
In this article, I will show you how to read PNG files in Java. We also have a related article covering how to write PNG files in Java.
As part of a separate project to provide customers with a solution to provide an easy way to convert PDF to PNG files in our JPedal software, we wanted better PNG support than we could find in ImageIO and other image libraries. So we wrote our own implementation and made it available as part of JDeli.
What is a PNG?
PNG stands for Portable Network Graphics. It is a lossless, bitmap image format popular on the world wide web because it supports transparency in browsers. It was created to remove the need for GIF images in web browsers. Unlike GIF, PNG is an open standard with no patents.
The file name extension for PNG files is: .png
How to read a PNG image in Java with ImageIO
Step 1 Create a File handle, InputStream, or URL pointing to the raw PNG image.
Step 2 ImageIO will now be able to read a PNG file into a BufferedImage. This syntax is like so:
BufferedImage image = ImageIO.read(pngFileOrInputStreamOrURL)
How to read a PNG image in Java with JDeli
Step 1 Add JDeli to your class or module path. (download the trial jar).
Step 2 Create a File handle or InputStream pointing to the raw PNG image. You can also use a byte[] containing the image data.
Step 3 Read the PNG image into a BufferedImage
BufferedImage image = JDeli.read(pngFile);
Download your JDeli guide:
Start reading and writing images with one line of code
Read: BufferedImage image = JDeli.read(streamOrFile);
Write: JDeli.write(myBufferedImage, OutputFormat.HEIC, outputStreamOrFile)
Bethan Palmer Bethan is a Java developer and a Java Champion. She has spoken at conferences including JavaOne/Code One, DevFest and NetBeans days. She has a degree in English Literature.