2

我编写了以下代码来将灰度图像的像素读取到一维数组中。运行代码时我怎么会出错

 public class LoadImage {
   BufferedImage image;
   void load()throws Exception { 
     File input = new File("lena.png");
     image = ImageIO.read(input);
   }
   public Dimension getImageSize() {
     return new Dimension(image.getWidth(), image.getHeight());
   }

   public int[] getImagePixels() {
     int [] dummy = null;
     int wid, hgt;

     // compute size of the array
     wid = image.getWidth();
     hgt = image.getHeight();

     // start getting the pixels
     Raster pixelData;
     pixelData = image.getData();
     return pixelData.getPixels(0, 0, wid, hgt, dummy);
   }
 }

主班

 public static void main(String[] args) throws IOException, Exception {
   LoadImage l = new LoadImage();
   l.load();
   int pixel[];
   pixel= l.getImagePixels();
 }
4

1 回答 1

1

好的,当您传递 File 对象时,问题来自 ImageIO.read 中的格式检测。试试这个:

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import javax.imageio.ImageIO;

public class LoadImage {
  BufferedImage image;
  void load() throws Exception { 
    image = ImageIO.read(getClass().getResourceAsStream("lena.png"));
  }

  public Dimension getImageSize() {
    return new Dimension(image.getWidth(), image.getHeight());
  }

  public int[] getImagePixels() {
    int [] dummy = null;
    int wid, hgt;

    // compute size of the array
    wid = image.getWidth();
    hgt = image.getHeight();

    // start getting the pixels
    Raster pixelData;
    pixelData = image.getData();

    System.out.println("wid:"+ wid);
    System.out.println("hgt:"+ hgt);
    System.out.println("Channels:"+pixelData.getNumDataElements());
    return pixelData.getPixels(0, 0, wid, hgt, dummy);
  }

  public static void main(String[] args) throws IOException, Exception {
    LoadImage l = new LoadImage();
    l.load();
    int[] pixel;
    pixel= l.getImagePixels();
    System.out.println("length:"+pixel.length);

    int height = 482;
    int width = 372;
    int channels = 3;
    int color = 0;

    BufferedImage red = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    BufferedImage green = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    BufferedImage blue = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        blue.setRGB(x, y, pixel[color * channels]);
        green.setRGB(x, y, pixel[color * channels + 1] << 8);
        red.setRGB(x, y, pixel[color * channels + 2] << 16);
        color++;
      }
    }
    ImageIO.write(red, "png", new File("red.png"));
    ImageIO.write(green, "png", new File("green.png"));
    ImageIO.write(blue, "png", new File("blue.png"));
  }
}

当我传递一个 372x482(24 位(3 通道)颜色)的 PNG 时,我得到

wid:372
hgt:482
Channels:3
length:537912

并且使用更新的代码这就是您如何获取它返回的数组并将每个通道保存回文件的方法。

于 2013-03-05T19:20:12.217 回答