You are on page 1of 6

Java BufferedImage - how to get the RGB value of each image pixel package com.devdaily.

imagetests; import import import import java.awt.Component; java.awt.image.BufferedImage; java.io.IOException; javax.imageio.ImageIO;

public class JavaWalkBufferedImageTest1 extends Component { public static void main(String[] foo) { new JavaWalkBufferedImageTest1(); } public void printPixelARGB(int pixel) { int alpha = (pixel >> 24) & 0xff; int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = (pixel) & 0xff; System.out.println("argb: " + alpha + ", " + red + ", " + green + ", " + blu e); } private void marchThroughImage(BufferedImage image) { int w = image.getWidth(); int h = image.getHeight(); System.out.println("width, height: " + w + ", " + h); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { System.out.println("x,y: " + j + ", " + i); int pixel = image.getRGB(j, i); printPixelARGB(pixel); System.out.println(""); } } } public JavaWalkBufferedImageTest1() { try { // get the BufferedImage, using the ImageIO class BufferedImage image = ImageIO.read(this.getClass().getResource("WhiteSpot.jpg")); marchThroughImage(image); } catch (IOException e) { System.err.println(e.getMessage()); } } } ******************************************************************************** ******************* Convert Image to Byte Array public byte[] extractBytes (String ImageName) throws IOException { // open image File imgPath = new File(ImageName); BufferedImage bufferedImage = ImageIO.read(imgPath);

// get DataBufferBytes from Raster WritableRaster raster = bufferedImage .getRaster(); DataBufferByte data = (DataBufferByte) raster.getDataBuffer(); return ( data.getData() ); } ------------------------------------------------------------Check out javax.imageio, especially ImageReader and ImageWriter as an abstractio n for reading and writing image files. BufferedImage.getRGB(int x, int y) than allows you to get RGB values on the give n pixel, which can be chunked into bytes. Note: I think you don't want to read the raw bytes, because then you have to dea l with all the compression/decompression. -------------------------------------------------------------File fnew=new File("/tmp/rose.jpg"); BufferedImage originalImage=ImageIO.read(fnew); ByteArrayOutputStream baos=new ByteArrayOutputStream(); ImageIO.write(originalImage, "jpg", baos ); byte[] imageInByte=baos.toByteArray(); ------------------------------------------------------------------/** * Reads the local image resource and returns an * array of bytes representing the image * @param imgPath path to the image inside the app * @return array of bytes representing the image */ public byte[] loadFromApp(String imgPath) { byte[] imgBytes = null; ByteArrayOutputStream baos = null; InputStream in = null; try { baos = new ByteArrayOutputStream(); //this image is inside my mobile application in = this.getClass().getResourceAsStream(imgPath); byte[] buffer = new byte[1024]; int n = 0; while ((n = in.read(buffer)) != -1) { baos.write(buffer, 0, n); } imgBytes = baos.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } finally { //whatever happends close the streams if (baos != null) { try {

baos.close(); } catch (Exception ex) { } } if (in != null) { try { in.close(); } catch (Exception ex) { } } } return imgBytes; } ******************************************************************************** ******************************** Convert Byte Array to Image : try { final BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputS tream(myByteArray)); ImageIO.write(bufferedImage, "jpg", new File("path/to/image.jpg")); } catch (IOException e) { e.printStackTrace(); } ---------------------------------------------------------------------------import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import import import import import import import java.util.Iterator; java.util.logging.Level; java.util.logging.Logger; javax.imageio.ImageIO; javax.imageio.ImageReadParam; javax.imageio.ImageReader; javax.imageio.stream.ImageInputStream;

public class ConvertImage { public static void main(String[] args) throws FileNotFoundException, IOExcep tion { /* * In this function the first part shows how to convert an image file to * byte array. The second part of the code shows how to change byte arra y * back to a image. */ File file = new File("C:\\rose.jpg"); System.out.println(file.exists() + "!!");

FileInputStream fis = new FileInputStream(file); //create FileInputStream which obtains input bytes from a file in a file system //FileInputStream is meant for reading streams of raw bytes such as imag e data. For reading streams of characters, consider using FileReader. //InputStream in = resource.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; try { for (int readNum; (readNum = fis.read(buf)) != -1;) { bos.write(buf, 0, readNum); //no doubt here is 0 /*Writes len bytes from the specified byte array starting at off set off to this byte array output stream.*/ System.out.println("read " + readNum + " bytes,"); } } catch (IOException ex) { Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, nul l, ex); } byte[] bytes = bos.toByteArray(); //bytes is the ByteArray we need /* * The second part shows how to convert byte array back to an image file */ //Before is how to change ByteArray back to Image ByteArrayInputStream bis = new ByteArrayInputStream(bytes); Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg"); //ImageIO is a class containing static convenience methods for locating ImageReaders //and ImageWriters, and performing simple encoding and decoding. ImageReader reader = (ImageReader) readers.next(); Object source = bis; // File or InputStream, it seems file is OK ImageInputStream iis = ImageIO.createImageInputStream(source); //Returns an ImageInputStream that will take its input from the given Ob ject reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); Image image = reader.read(0, param); //got an image file BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), im age.getHeight(null), BufferedImage.TYPE_INT_RGB); //bufferedImage is the RenderedImage to be written Graphics2D g2 = bufferedImage.createGraphics(); g2.drawImage(image, null, null); File imageFile = new File("C:\\newrose2.jpg"); ImageIO.write(bufferedImage, "jpg", imageFile); //"jpg" is the format of the image //imageFile is the file to be written to.

System.out.println(imageFile.getPath()); } } ------------------------------------------------------------------------------------------------------import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; public class SimpleConvertImage { public static void main(String[] args) throws IOException{ String dirName="C:\\"; ByteArrayOutputStream baos=new ByteArrayOutputStream(1000); BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg")); ImageIO.write(img, "jpg", baos); baos.flush(); String base64String=Base64.encode(baos.toByteArray()); baos.close(); byte[] bytearray = Base64.decode(base64String); BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearr ay)); ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg")); } } ------------------------------------------------------------------package com.mkyong.image; import import import import import import import java.awt.image.BufferedImage; java.io.ByteArrayInputStream; java.io.ByteArrayOutputStream; java.io.File; java.io.IOException; java.io.InputStream; javax.imageio.ImageIO;

public class ImageTest { public static void main(String[] args) { try { byte[] imageInByte; BufferedImage originalImage = ImageIO.read(new File( "c:/darksouls.jpg")); // convert BufferedImage to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream() ; ImageIO.write(originalImage, "jpg", baos); baos.flush();

imageInByte = baos.toByteArray(); baos.close(); // convert byte array back to BufferedImage InputStream in = new ByteArrayInputStream(imageInByte); BufferedImage bImageFromConvert = ImageIO.read(in); ImageIO.write(bImageFromConvert, "jpg", new File( "c:/new-darksouls.jpg")); } catch (IOException e) { System.out.println(e.getMessage()); } } } ---------------------------------------------------------------------------------

You might also like