Advertisement
Guest User

Untitled

a guest
Aug 1st, 2013
649
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. // tested on this image http://www.goabroad.com/blog/wp-content/uploads/2012/10/GACoverPhotoContest.jpg
  2.  
  3. int pixels[][] = convertTo2DWithoutUsingGetRGB(image);
  4.  
  5. boolean withAlpha = false; // if you need the alpha channel change this to true
  6. String imgFormat = "jpg";  // if you need the alpha channel change this to png
  7. String imgPath   = "myImage." + imgFormat;
  8.  
  9. BufferedImage newImg = getImage(pixels, withAlpha);
  10.  
  11. ImageIO.write(newImg, imgFormat, new File(imgPath));
  12.  
  13. private static BufferedImage getImage(int[][] pixels, final boolean withAlpha)
  14. {
  15.   // Assuming pixels was taken from convertTo2DWithoutUsingGetRGB
  16.   // i.e. img.length == pixels.length and img.width == pixels[x].length
  17.   BufferedImage img = new BufferedImage(pixels[0].length, pixels.length, withAlpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR);
  18.   for (int y = 0; y < pixels.length; y++)
  19.   {
  20.      for (int x = 0; x < pixels[y].length; x++)
  21.      {
  22.         if (withAlpha)
  23.            img.setRGB(x, y, pixels[y][x]);
  24.         else {
  25.            int pixel = pixels[y][x];
  26.            int alpha = (pixel >> 24 & 0xff);
  27.            int red   = (pixel >> 16 & 0xff);
  28.            int green = (pixel >> 8 & 0xff);
  29.            int blue  = (pixel & 0xff);
  30.            int rgb = (red << 16) | (green << 8) | blue;
  31.            img.setRGB(x, y, rgb);
  32.         }
  33.      }
  34.   }
  35.   return img;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement