java 图片有损压缩_java - 用有损jpeg压缩多页tiff图像 - 堆栈内存溢出

将图像从16位减少到8位。 假设您有一个byte []变量plane16,在其中您有图像的所有像素。

注意 :我的byte [] plane16从16位图像获取数据,但是byte为8bit = 1byte。 因此,此数组行中的2个元素为2byte = 16bit。 这就是为什么我在操作之前将其转换为short []的原因。 如果从short []开始,则省略“ ByteBuffer.wrap(plane16).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()。get(shorts);”

byte[] plane16; //Fill it with your image!!!

//Do stuff with imageIO. Set writer and compresion method

ImageIO.scanForPlugins();

TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi();

javax.imageio.ImageWriter writerIO = tiffspi.createWriterInstance();

ImageWriteParam param = writerIO.getDefaultWriteParam();

param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

param.setCompressionType("ZLib");

param.setCompressionQuality(0.5f);

File fOutputFile = new File(route+".tif");

ImageOutputStream ios = ImageIO.createImageOutputStream(fOutputFile);

writerIO.setOutput(ios);

//Reducing 16bit to 8bit

short[] shorts = new short[plane16.length/2];

ByteBuffer.wrap(plane16).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);

int max = 0;

int min = 999999;

for (int v = 0; v

if (max

if (min>shorts[v]) min = shorts[v];

}

double range = 255./(max-min);

byte[] plane8 = new byte[shorts.length];

for (int v = 0; v

plane8[v] = (byte) ((shorts[v]+min)*range - 128);

}

//16bit:

/*BufferedImage convertedGrayscale = new BufferedImage(width,

heigth, BufferedImage.TYPE_USHORT_GRAY);

convertedGrayscale.getRaster().setDataElements(0, 0, width,

heigth, shorts);*/

//8bit:

BufferedImage convertedGrayscale = new BufferedImage(width,

heigth, BufferedImage.TYPE_BYTE_GRAY);

convertedGrayscale.getRaster().setDataElements(0, 0, width,

heigth, plane8);

//Save image

//If you have a stack of images in tiff, do this trick. "image" is the image number you are setting inside the tiff. If you only have 1 image, remove the if and take the expression from the else.

if (image!=0){

writerIO.writeInsert(image, new IIOImage(convertedGrayscale, null, null), param);

}else{

writerIO.write(null, new IIOImage(convertedGrayscale, null, null), param);

}

//do the next only after the last image to be saved

writerIO.dispose();

ios.flush();

ios.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值