【问题标题】:8 bit gray scale image byte array to jpg8位灰度图像字节数组到jpg
【发布时间】:2014-12-02 20:44:34
【问题描述】:

我正在尝试将 8 位灰度图像字节数组转换为 java 中的 jpg 图像格式。

static byte[] bytes = new byte[]{126, 126, 127, -128};

public static void main(String[] args) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
    ImageReader reader = (ImageReader) readers.next();
    Object source = bis; 
    ImageInputStream iis = ImageIO.createImageInputStream(source); 
    reader.setInput(iis, true);
    ImageReadParam param = reader.getDefaultReadParam();
    Image image = reader.read(0, param);
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_GRAY);
    Graphics2D g2 = bufferedImage.createGraphics();
    g2.drawImage(image, null, null);
    File imageFile = new File("C:\\newrose3.jpg");
    ImageIO.write(bufferedImage, "jpg", imageFile);
    System.out.println(imageFile.getPath());
}

我有包含图像数据的字节,我想在 java 中将其转换为可读的图像格式。

【问题讨论】:

  • 你有什么问题?
  • 我的问题是如何将图像字节数组 {126, 126, 127, -128} 转换为任何可读的图像格式?
  • {126, 126, 127, -128} 应该是什么格式?对于完整的 JPEG 流来说,它有点短。那是像素值吗?
  • 是的,这是灰度像素数据

标签: java image image-processing


【解决方案1】:

假设bytes 应该是像素数据,您应该从这些字节创建图像,然后将其写为JPEG。

类似:

// Create an image type grayscale
BufferedImage image = new BufferedImage(2, 2, BufferedImage.TYPE_BYTE_GRAY);

// Get the backing pixels, and copy into it
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(bytes, 0, data, 0, bytes.length);

// Write it out:
ImageIO.write(image, "jpg", new File("yourPathHere");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多