简体   繁体   English

如何在Java中创建新的灰度(BufferedImage.TYPE_BYTE_GRAY)图像?

[英]How to create a new grey scale (BufferedImage.TYPE_BYTE_GRAY) image in java?

I want to create a grayscale image but problem is that how I can specify the value (0-255) for a pixel and read it during reading the same image. 我想创建一个灰度图像,但是问题是如何为像素指定值(0-255)并在读取同一图像时读取它。

     BufferedImage img = new BufferedImage(width, height , BufferedImage.TYPE_BYTE_GRAY);
            File file = null; 
            //create random image pixel by pixel
            for(int yHeight = 0; yHeight < height; yHeight++){ 
             for(int xWidth = 0; xWidth < width; xWidth++){ 
               img.setRGB(xWidth, yHeight, rgb);//here what values to specify 
               //for rgb (0-255)
                 }      
             }

//write image
             try{
               file = new File("D:\\Output.png");
               ImageIO.write(img, "png", file);

             }catch(IOException e){
               System.out.println("Error: " + e);
             }

and for reading the same image how can I get the same specified pixel value. 为了读取相同的图像,我如何获得相同的指定像素值。

private static void marchThroughImage(BufferedImage image) {
        int w = image.getWidth();
        int h = image.getHeight();

        for (int i = 0; i < h; i++) {
          for (int j = 0; j < w; j++) {
            int pixel = image.getRGB(j, i);
           }
         }
      }

There are two different parts in your question: 您的问题有两个不同的部分:

  • First to read / write an image in Java, you should use Java.imageio using this simple code 首先使用Java读取/写入图像,您应该使用此简单代码使用Java.imageio

    BufferedImage image = javax.imageio.ImageIO.read(new File("path/to/the/image")) ; boolean written = javax.imageio.ImageIO.write(image, "png", new File("where/to/write/the/image")) ;

  • Then to access / modify the pixels in your image, you should access the raster with getSample / setSample or if you need performance, you directly access the DataBuffer. 然后,要访问/修改图像中的像素,应使用getSample / setSample访问栅格,或者如果需要性能,则可以直接访问DataBuffer。 Read my answer in this question: Efficient access to image pixels in Java 阅读我对以下问题的回答: 有效访问Java中的图像像素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM