jpeg rgba compress

50 阅读1分钟
public static ByteArrayOutputStream getImgByteArrayOutputStream(byte[] rgba,int width, int height, String imageType) {
    int capacity = height * width * 3;
    ByteArrayOutputStream os = new ByteArrayOutputStream(capacity);
    try{// 定义每像素字节数
        int bytePerPixel = 4;
        if(null != rgba && rgba.length != width*height*bytePerPixel){
            throw new RuntimeException("invalid image description");
        }
        // 将图像数据byte[]封装为DataBuffer
        DataBufferByte dataBuffer = null == rgba ? null : new DataBufferByte(rgba, rgba.length);
        // 定义色彩空间 sRGB
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        int[] bOffs = {0,1,2};
        // 根据色彩空间创建色彩模型(ColorModel实例),bOffs用于定义R,G,B三个分量在每个像素数据中的位置
        ComponentColorModel colorModel = new ComponentColorModel(cs, false, false,
                Transparency.OPAQUE,
                DataBuffer.TYPE_BYTE);
        // 从DataBuffer创建光栅对象Raster
        WritableRaster raster = null != dataBuffer
                ? Raster.createInterleavedRaster(dataBuffer, width, height, width*bytePerPixel, bytePerPixel, bOffs, null)
                : Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height,width*bytePerPixel, bytePerPixel, bOffs, null);
        BufferedImage img = new BufferedImage(colorModel,raster,colorModel.isAlphaPremultiplied(),null);
        ImageIO.setUseCache(false);
        ImageIO.write(img, imageType.replace(".",""), os);
        return os;
    } catch (Exception e){
        log.info("picture make failed ", e);
    }
    return null;
}