Search code examples
javaimagecropbufferedimagepixel

Creating/Cropping image base on number of pixels Java


How can i crop an image to a specified number of pixels or create image that the output will be base on number of pixel not rectangular shape. By using the code below i can only get square or rectangle shape.

BufferedImage out = img.getSubimage(0, 0, 11, 11);

But it only crops it to rectangular shape

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
  public class raNd{
  public static void main(String args[])throws IOException{
    //image dimension
    int width = 10;
    int height = 10;
    //create buffered image object img
    BufferedImage img = new BufferedImage(width, height, 
    BufferedImage.TYPE_INT_ARGB);
    //file object
    File f = null;
    //create random image pixel by pixel
    for(int y = 0; y < height; y++){
      for(int x = 0; x < width; x++){
        int a = 255;//(int)(Math.random()*256); //alpha
        int r = (int)(Math.random()*256); //red
        int g = (int)(Math.random()*256); //green
        int b = (int)(Math.random()*256); //blue
        int p = (a<<24) | (r<<16) | (g<<8) | b; //pixel
        img.setRGB(x, y, p);
      }
    }
    //write image
    try{
      f = new File("/Users/kingamada/Documents/Java/Test6.png");
      BufferedImage out = img.getSubimage(0, 0, 5, 2);
      ImageIO.write(out, "png", f);
    }catch(IOException e){
    System.out.println("Error: " + e);
   }
  }//main() ends here
}//class ends here

Sample Picture

I want the last white pixels cropped out, so the picture will not be rectangle.


Solution

  • So assuming the number of pixels you need to keep is in variable int pixelsLimit;:

    int pixels = 0;
    for(int y = 0; y < height; y++){
      for(int x = 0; x < width; x++){
        int p = 0;
        if (pixels < pixelsLimit) {
            int a = 255;//(int)(Math.random()*256); //alpha
            int r = (int)(Math.random()*256); //red
            int g = (int)(Math.random()*256); //green
            int b = (int)(Math.random()*256); //blue
            p = (a<<24) | (r<<16) | (g<<8) | b; //pixel
        }
        img.setRGB(x, y, p);
        ++pixels;
      }
    }