图片压缩工具

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
* 图像压缩工具
*
*/
public class ImageSizer {
public static final MediaTracker tracker = new MediaTracker(new Component() {
private static final long serialVersionUID = 1234162663955668507L;}
);
/**
* @param originalFile 原图像
* @param resizedFile 压缩后的图像
* @param width 图像宽
* @param format 图片格式 jpg, png, gif(非动画)
* @throws IOException
*/
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {
if(format!=null && "gif".equals(format.toLowerCase())){
resize(originalFile, resizedFile, width, 1);
return;
}
FileInputStream fis = new FileInputStream(originalFile);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int readLength = -1;
int bufferSize = 1024;
byte bytes[] = new byte[bufferSize];
while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
byteStream.write(bytes, 0, readLength);
}
byte[] in = byteStream.toByteArray();
fis.close();
byteStream.close();

Image inputImage = Toolkit.getDefaultToolkit().createImage( in );
waitForImage( inputImage );
int imageWidth = inputImage.getWidth( null );
if ( imageWidth < 1 )
throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
int imageHeight = inputImage.getHeight( null );
if ( imageHeight < 1 )
throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );

// Create output image.
int height = -1;
double scaleW = (double) imageWidth / (double) width;
double scaleY = (double) imageHeight / (double) height;
if (scaleW >= 0 && scaleY >=0) {
if (scaleW > scaleY) {
height = -1;
} else {
width = -1;
}
}
Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);
checkImage( outputImage );
encode(new FileOutputStream(resizedFile), outputImage, format);
}

/** Checks the given image for valid width and height. */
private static void checkImage( Image image ) {
waitForImage( image );
int imageWidth = image.getWidth( null );
if ( imageWidth < 1 )
throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
int imageHeight = image.getHeight( null );
if ( imageHeight < 1 )
throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
}

/** Waits for given image to load. Use before querying image height/width/colors. */
private static void waitForImage( Image image ) {
try {
tracker.addImage( image, 0 );
tracker.waitForID( 0 );
tracker.removeImage(image, 0);
} catch( InterruptedException e ) { e.printStackTrace(); }
}

/** Encodes the given image at the given quality to the output stream. */
private static void encode( OutputStream outputStream, Image outputImage, String format )
throws java.io.IOException {
int outputWidth = outputImage.getWidth( null );
if ( outputWidth < 1 )
throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" );
int outputHeight = outputImage.getHeight( null );
if ( outputHeight < 1 )
throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" );

// Get a buffered image from the image.
BufferedImage bi = new BufferedImage( outputWidth, outputHeight,
BufferedImage.TYPE_INT_RGB );
Graphics2D biContext = bi.createGraphics();
biContext.drawImage( outputImage, 0, 0, null );
ImageIO.write(bi, format, outputStream);
outputStream.flush();
}

/**
* 缩放gif图片
* @param originalFile 原图片
* @param resizedFile 缩放后的图片
* @param newWidth 宽度
* @param quality 缩放比例 (等比例)
* @throws IOException
*/
private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
if (quality < 0 || quality > 1) {
throw new IllegalArgumentException("Quality has to be between 0 and 1");
}
ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage = null;
int iWidth = i.getWidth(null);
int iHeight = i.getHeight(null);
if (iWidth > iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
} else {
resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
}
// This code ensures that all the pixels in the image are loaded.
Image temp = new ImageIcon(resizedImage).getImage();
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
// Soften.
float softenFactor = 0.05f;
float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
bufferedImage = cOp.filter(bufferedImage, null);
// Write the jpeg to a file.
FileOutputStream out = new FileOutputStream(resizedFile);
// Encodes image as a JPEG data stream
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
param.setQuality(quality, true);
encoder.setJPEGEncodeParam(param);
encoder.encode(bufferedImage);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android图片压缩工具类是一种用于压缩Android应用中的图片文件的工具。根据引用和引用的内容,这个工具类的具体实现可能包括以下功能: - 通过将图片文件转换为字节数组,以便进行后续的压缩处理。 - 使用缓冲输出流将压缩后的图片数据写入输出流中。 - 通过设置合适的压缩参数,对图片进行压缩操作,减小文件大小但尽量保持良好的图像质量。 - 可能还包括一些其他的图像处理操作,如旋转、裁剪等。 具体的实现细节可以参考引用和引用提供的代码示例。在这些示例中,使用了ByteArrayInputStream和ByteArrayOutputStream类来处理字节数组的输入和输出。通过设置合适的压缩参数,可以实现对图片的压缩操作。此外,还可以使用BufferedOutputStream类来提高输出流的写入性能。 如果想要进一步了解关于Android图片压缩工具类的使用和实现细节,可以参考引用提供的配套资料,该资料可能提供了更详细的解释和示例代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Android开发之图片压缩工具类完整实例](https://download.csdn.net/download/weixin_38517904/14018839)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [android图片压缩工具类分享](https://download.csdn.net/download/weixin_38616330/14881444)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Spring Boot(六十四):SpringBoot集成Gzip压缩数据](https://download.csdn.net/download/u013938578/88221156)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值