How can I write 16 bit grayscale image as jpeg?

回眸只為那壹抹淺笑 提交于 2021-01-27 11:52:27

问题


I have 16-bit per pixel grayscale BufferedImage created from an array of shorts:

 private BufferedImage get16bitImage(short[] pixels) {
    ColorModel colorModel = new ComponentColorModel(
            ColorSpace.getInstance(ColorSpace.CS_GRAY),
            new int[]{16},
            false,
            false,
            Transparency.OPAQUE,
            DataBuffer.TYPE_USHORT);
    DataBufferUShort db = new DataBufferUShort(pixels, pixels.length);
    WritableRaster raster = Raster.createInterleavedRaster(
            db,
            imgD.width,
            imgD.height,
            imgD.width,
            1,
            new int[1],
            null);
    return new BufferedImage(colorModel, raster, false, null);
}

When trying to save it:

  ImageIO.write(img, "PNG", new File(resultImgNamePNG)); // works fine
  ImageIO.write(img, "BMP", new File(resultImgNameBMP)); // doesn't work, returns false
  ImageIO.write(img, "JPEG", new File(resultImgNameJPEG)); // doesnt work, returns false

I tried using JAI:

public void writeImageToJPEG(File out, BufferedImage image, float quality) throws IOException {
    JPEGEncodeParam param = new JPEGEncodeParam();
    param.setQuality(quality);
    ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", new FileOutputStream(out), param);

    encoder.encode(image);
}

encoder.encode(image) throws java.lang.RuntimeException: Only 1, or 3-band byte data may be written.


回答1:


I think you have to convert it to 8-bit first. If this is used for display purposes, java converts it to 8-bit bit before display anyways.

You can do something that I've seen sometimes actually improve the displayed image which is doing non-linear scaling of the values (using a log scale for example) such detail depends on the image you are generating ofcourse.

More on such effect here: http://www.java.net/external?url=http://www.cs.unm.edu/~brayer/vision/perception.html



来源:https://stackoverflow.com/questions/8982651/how-can-i-write-16-bit-grayscale-image-as-jpeg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!