8位灰度图像字节数组到jpg

时间:2014-12-02 12:17:34

标签: java image image-processing

我正在尝试将java中的8位灰度图像字节数组转换为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中将其转换为可读的图像格式。

1 个答案:

答案 0 :(得分:2)

假设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");