Creating/Cropping 基于像素数的图像 Java

Creating/Cropping image base on number of pixels Java

如何将图像裁剪为指定的像素数或创建输出基于像素数而不是矩形的图像。 通过使用下面的代码,我只能得到正方形或长方形。

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

但它只会将其裁剪为矩形

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

我希望裁剪掉最后的白色像素,这样图片就不会是矩形了。

Java 图片是矩形的,但是有人建议你可以设置你不想透明的像素。

Ellipse2D clip = new Ellipse2D.Double(0, 0, width, height);

for(int y = 0; y < height; y++){
  for(int x = 0; x < width; x++){
    if(!clip.contains(x,y)){
      img.setRGB(x, y, 0);
    }
  }
}

这可以直接添加到现有代码中,使您的图像成为椭圆。另一种方法是使用剪裁形状和图形对象。我已经替换了你完整的写入图像块。

//write image
try{

  f = new File("Test6.png");

  Ellipse2D clip = new Ellipse2D.Double(0, 0, width, height);
  BufferedImage clipped = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  Graphics g = clipped.getGraphics();
  g.setClip(clip); //ellipse from above.
  g.drawImage(img, 0, 0, null);
  g.dispose();
  ImageIO.write(clipped, "png", f);
}catch(IOException e){
  System.out.println("Error: " + e);
}

这为我编译并写了一个微小的圆形图像。

因此假设您需要保留的像素数在变量 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;
  }
}