基于像素数Java创建/裁剪图像

时间:2018-03-26 06:44:15

标签: java image crop bufferedimage pixels

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

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

我希望裁剪掉最后一个白色像素,因此图片不会是矩形。

2 个答案:

答案 0 :(得分:0)

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);
}

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

答案 1 :(得分:0)

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