java图像压缩

本文探讨了远程监控程序中使用不同图像压缩方法(JPEG、GZIP)及结合使用以减小图片文件大小并提高传输效率的实践。通过对比PNG与JPEG格式在复杂与简单图像上的表现,提出了在保持图像质量的同时降低资源消耗的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在写一个远程监控程序,要对屏幕截图,发送到另一台电脑。
网上找到了两种图像压缩和解压的方法
1.

        //压缩
        public static ByteArrayOutputStream encodeImage(BufferedImage image)throws ImageFormatException, IOException{


		ByteArrayOutputStream out = new ByteArrayOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
		param.setQuality(0.5f, false);
		encoder.setJPEGEncodeParam(param);
		encoder.encode(image);
		return out;
		
	}
        
        //解压
	public static BufferedImage decodeImage(ByteArrayInputStream in)throws ImageFormatException, IOException{
		com.sun.image.codec.jpeg.JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
		BufferedImage image = decoder.decodeAsBufferedImage();

		in.close();
		return image;
	}



2.
    //压缩
    private ByteArrayOutputStream gzip(ByteArrayOutputStream bas) throws IOException{
		ByteArrayOutputStream zippedBas = new ByteArrayOutputStream();
		GZIPOutputStream gz = new GZIPOutputStream(zippedBas);
		gz.write(bas.toByteArray());
		gz.flush();
		gz.close();
		return zippedBas;
	}
    //用GZIPInputStream 解压,直接从流中读取就行


3.还有就是用ImageIO.write()方法也很好用。

比较:
我发现对于比较复杂的图像(比如桌面背景),用ImageIO.write(),保存为png格式的会比jpg占空间小,但jpg也还行;但是一般的图像(比如打开word文档或浏览网页时的屏幕图像这种有一大堆空白的)用jpg比较小。另外,我用第一和第二种方法相结合,先 JPEGImageEncoder压缩后在GZip压缩,效果还行。当然图像质量差了很多,不过对于远程监控足够了

转载于:https://my.oschina.net/soitravel/blog/33570

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值