JAVA将任意图片文件压缩成想要的图片类型与大小
java 实现对图片进行指定的缩小或放大

2010-02-02java 实现对图片进行指定的缩小或放大文章分类:Java编程package common.util;import java.awt.Color;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Rectangle;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.awt.image.ColorModel;import java.awt.image.WritableRaster;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;/*** 图片工具类,完成图片的截取** @author inc062977**/public class AlterUploadImage {/*** 实现图像的等比缩放* @param source* @param targetW* @param targetH* @return*/private static BufferedImage resize(BufferedImage source, int targetW,int targetH) {// targetW,targetH分别表示目标长和宽int type = source.getType();BufferedImage target = null;double sx = (double) targetW / source.getWidth();double sy = (double) targetH / source.getHeight();// 这里想实现在targetW,targetH范围内实现等比缩放。
java实现图片像素质量压缩与图片长宽缩放

java实现图⽚像素质量压缩与图⽚长宽缩放⽬录java 图⽚像素质量压缩与图⽚长宽缩放java 修改图⽚dpi(像素/⼤⼩)java 图⽚像素质量压缩与图⽚长宽缩放今天找到的这个⽅法⽐以前项⽬⽤到的⽅法更好,这⾥记录下,⽅便⽇后使⽤!/*** 缩放图⽚(压缩图⽚质量,改变图⽚尺⼨)* 若原图宽度⼩于新宽度,则宽度不变!* @param newWidth 新的宽度* @param quality 图⽚质量参数 0.7f 相当于70%质量* 2015年12⽉11⽇*/public static void resize(File originalFile, File resizedFile,int newWidth, float quality) throws IOException {if (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 < newWidth){newWidth = iWidth;}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 streamJPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);param.setQuality(quality, true);encoder.setJPEGEncodeParam(param);encoder.encode(bufferedImage);} // Example usagepublic static void main(String[] args) throws IOException {// File originalImage = new File("C:\\11.jpg");// resize(originalImage, new File("c:\\11-0.jpg"),150, 0.7f);// resize(originalImage, new File("c:\\11-1.jpg"),150, 1f);File originalImage = new File("d:\\testImg\\1.jpg");System.out.println("源⽂件⼤⼩" + originalImage.length());// File resizedImg = new File("d:\\testImg\\11.jpg");// resize(originalImage, resizedImg, 850, 1f);// System.out.println("0.5转换后⽂件⼤⼩" + resizedImg.length());// File resizedImg1 = new File("d:\\testImg\\111.jpg");File resizedImg1 = new File("/alidata/zkyj/dashixiong/tempImgFile/11.jpg");resize(originalImage, resizedImg1, 1550, 0.7f);System.out.println("0.7转换后⽂件⼤⼩" + resizedImg1.length());}java 修改图⽚dpi(像素/⼤⼩)import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGEncodeParam;import com.sun.image.codec.jpeg.JPEGImageEncoder;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;public class DPIHandleHelper {private static int DPI = 300;public static void main(String[] args) {String path = "C:\\test.jpg";File file = new File(path);handleDpi(file, 300, 300);}/*** 改变图⽚DPI** @param file* @param xDensity* @param yDensity*/public static void handleDpi(File file, int xDensity, int yDensity) {try {BufferedImage image = ImageIO.read(file);JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(file)); JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);jpegEncodeParam.setQuality(0.75f, false);jpegEncodeParam.setXDensity(xDensity);jpegEncodeParam.setYDensity(yDensity);jpegEncoder.encode(image, jpegEncodeParam);image.flush();} catch (IOException e) {e.printStackTrace();}}}以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
java中实现压缩图片(指定图片宽度和高度或者压缩比例对图片进行压缩)

java中实现压缩图⽚(指定图⽚宽度和⾼度或者压缩⽐例对图⽚进⾏压缩)package com.thinkgem.jeesite.test;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;@SuppressWarnings("restriction")public class ReduceImgTest {/*** 指定图⽚宽度和⾼度或压缩⽐例对图⽚进⾏压缩** @param imgsrc 源图⽚地址* @param imgdist ⽬标图⽚地址* @param widthdist 压缩后图⽚的宽度* @param heightdist 压缩后图⽚的⾼度* @param rate 压缩的⽐例*/public static void reduceImg(String imgsrc, String imgdist, int widthdist, int heightdist, Float rate) {try {File srcfile = new File(imgsrc);// 检查图⽚⽂件是否存在if (!srcfile.exists()) {System.out.println("⽂件不存在");}// 如果⽐例不为空则说明是按⽐例压缩if (rate != null && rate > 0) {//获得源图⽚的宽⾼存⼊数组中int[] results = getImgWidthHeight(srcfile);if (results == null || results[0] == 0 || results[1] == 0) {return;} else {//按⽐例缩放或扩⼤图⽚⼤⼩,将浮点型转为整型widthdist = (int) (results[0] * rate);heightdist = (int) (results[1] * rate);}}// 开始读取⽂件并进⾏压缩Image src = ImageIO.read(srcfile);// 构造⼀个类型为预定义图像类型之⼀的 BufferedImageBufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);//绘制图像 getScaledInstance表⽰创建此图像的缩放版本,返回⼀个新的缩放版本Image,按指定的width,height呈现图像//Image.SCALE_SMOOTH,选择图像平滑度⽐缩放速度具有更⾼优先级的图像缩放算法。
java图片无损压缩

java图⽚⽆损压缩⼀,提供⼀张原图,原图⼤⼩2.1mb⼆,处理后图⽚⼤⼩对⽐,⼤⼩772kb,对⽐原图占⽤内存减少三分之⼆三,java代码3.1 本地压缩测试/**** @param srcFilePath 原图路径* @param descFilePath 保存路径* @return* @throws IOException*/public static boolean compressPic(String srcFilePath, String descFilePath) throws IOException {File file = null;BufferedImage src = null;FileOutputStream out = null;// 指定写图⽚的⽅式为 jpgImageWriter imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();ImageWriteParam imgWriteParams =new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);// 要使⽤压缩,必须指定压缩⽅式为MODE_EXPLICITimgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);// 这⾥指定压缩的程度,参数qality是取值0~1范围内,imgWriteParams.setCompressionQuality((float)1);imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);ColorModel colorModel = ImageIO.read(new File(srcFilePath)).getColorModel();// ColorModel.getRGBdefault();imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));try {if (StringUtils.isEmpty(srcFilePath)) {return false;} else {file = new File(srcFilePath);System.out.println(file.length());src = ImageIO.read(file);out = new FileOutputStream(descFilePath);imgWrier.reset();// 必须先指定 out值,才能调⽤write⽅法, ImageOutputStream可以通过任何// OutputStream构造imgWrier.setOutput(ImageIO.createImageOutputStream(out));// 调⽤write⽅法,就可以向输⼊流写图⽚imgWrier.write(null, new IIOImage(src, null, null),imgWriteParams);out.flush();out.close();}} catch (Exception e) {e.printStackTrace();return false;}return true;}public static void main(String[] args) throws IOException {String stpa="D:\\⽂件表\\test1.jpg";String st1="D:\\⽂件表\\test2.jpg";compressPic(stpa, st1);}3.2 也可压缩后转成数据格式返回做其他操作1/**2 *3 * ⾃⼰设置压缩质量来把图⽚压缩成byte[]4 *5 * @param image6 * 压缩源图⽚7 * @param quality8 * 压缩质量,在0-1之间,9 * @return 返回的字节数组10*/11private byte[] bufferedImageTobytes(BufferedImage image, float quality) {12// 如果图⽚空,返回空13/*if (image == null) {14 return null;15 } */16// 得到指定Format图⽚的writer17 Iterator<ImageWriter> iter = ImageIO18 .getImageWritersByFormatName("jpg");// 得到迭代器19 ImageWriter writer = (ImageWriter) iter.next(); // 得到writer2021// 得到指定writer的输出参数设置(ImageWriteParam )22 ImageWriteParam iwp = writer.getDefaultWriteParam();23 iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // 设置可否压缩24 iwp.setCompressionQuality(quality); // 设置压缩质量参数2526 iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED);2728 ColorModel colorModel = image.getColorModel();29// 指定压缩时使⽤的⾊彩模式30 iwp.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel,31 colorModel.createCompatibleSampleModel(16, 16)));3233// 开始打包图⽚,写⼊byte[]34 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 取得内存输出流35 IIOImage iIamge = new IIOImage(image, null, null);36try {37// 此处因为ImageWriter中⽤来接收write信息的output要求必须是ImageOutput38// 通过ImageIo中的静态⽅法,得到byteArrayOutputStream的ImageOutput39 writer.setOutput(ImageIO40 .createImageOutputStream(byteArrayOutputStream));41 writer.write(null, iIamge, iwp);4243 } catch (IOException e) {44 System.out.println("write errro");45 e.printStackTrace();46 }47return byteArrayOutputStream.toByteArray();48 }。
JAVA图片压缩到指定大小

JAVA图⽚压缩到指定⼤⼩这是压缩到⼩于300KB的,循环压缩,⼀次不⾏再压⼀次,不废话,直接贴代码<!-- 图⽚缩略图 --><dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency><dependency><groupId>mons</groupId><artifactId>commons-lang3</artifactId></dependency><!--<dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId></dependency>--><dependency><groupId>mons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dependency><dependency><groupId>mons</groupId><artifactId>commons-collections4</artifactId><version>4.4</version></dependency>package com.uniview.keepalive.util;import lombok.extern.slf4j.Slf4j;import net.coobird.thumbnailator.Thumbnails;import mons.io.FileUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;@Slf4jpublic class PicUtils {private static Logger logger = LoggerFactory.getLogger(PicUtils.class);public static void main(String[] args) throws IOException {byte[] bytes = FileUtils.readFileToByteArray(new File("C:\\Users\\Administrator\\Desktop\\邓111111.jpg"));long l = System.currentTimeMillis();bytes = pressPicForScale(bytes, 300, "x");// 图⽚⼩于300kbSystem.out.println(System.currentTimeMillis() - l);FileUtils.writeByteArrayToFile(new File("C:\\Users\\Administrator\\Desktop\\邓11111压缩后.jpg"), bytes);}/*** 根据指定⼤⼩压缩图⽚** @param imageBytes 源图⽚字节数组* @param desFileSize 指定图⽚⼤⼩,单位kb* @param imageId 影像编号* @return压缩质量后的图⽚字节数组*/public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) { if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {return imageBytes;}long srcSize = imageBytes.length;double accuracy = getAccuracy(srcSize / 1024);try {while (imageBytes.length > desFileSize * 1024) {ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length); Thumbnails.of(inputStream).scale(accuracy).outputQuality(accuracy).toOutputStream(outputStream);imageBytes = outputStream.toByteArray();}("【图⽚压缩】imageId={} | 图⽚原⼤⼩={}kb | 压缩后⼤⼩={}kb",imageId, srcSize / 1024, imageBytes.length / 1024);} catch (Exception e) {logger.error("【图⽚压缩】msg=图⽚压缩失败!", e);}return imageBytes;}/*** ⾃动调节精度(经验数值)** @param size 源图⽚⼤⼩* @return图⽚压缩质量⽐*/private static double getAccuracy(long size) {double accuracy;if (size < 900) {accuracy = 0.85;} else if (size < 2047) {accuracy = 0.6;} else if (size < 3275) {accuracy = 0.44;} else {accuracy = 0.4;}return accuracy;}}。
Java实现的上传并压缩图片功能【可等比例压缩或原尺寸压缩】

Java实现的上传并压缩图⽚功能【可等⽐例压缩或原尺⼨压缩】本⽂实例讲述了Java实现的上传并压缩图⽚功能。
分享给⼤家供⼤家参考,具体如下:先看效果:原图:1.33M处理后:27.4kb关键代码:package codeGenerate.util;import java.awt.Color;import java.awt.Graphics2D;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import javax.imageio.ImageIO;public class ImageZipUtil {public static void main(String[] args) {zipWidthHeightImageFile(new File("C:\\spider\\3.png"),new File("C:\\spider\\3-1.jpg"),425,638,0.7f);//zipImageFile(new File("C:\\spider\\2.JPG"),new File("C:\\spider\\2-2.JPG"),425,638,0.7f);//zipImageFile(new File("C:\\spider\\3.jpg"),new File("C:\\spider\\3-3.jpg"),425,638,0.7f);System.out.println("ok");}/*** 根据设置的宽⾼等⽐例压缩图⽚⽂件<br> 先保存原⽂件,再压缩、上传* @param oldFile 要进⾏压缩的⽂件* @param newFile 新⽂件* @param width 宽度 //设置宽度时(⾼度传⼊0,等⽐例缩放)* @param height ⾼度 //设置⾼度时(宽度传⼊0,等⽐例缩放)* @param quality 质量* @return 返回压缩后的⽂件的全路径*/public static String zipImageFile(File oldFile,File newFile, int width, int height,float quality) {if (oldFile == null) {return null;}try {/** 对服务器上的临时⽂件进⾏处理 */Image srcFile = ImageIO.read(oldFile);int w = srcFile.getWidth(null);int h = srcFile.getHeight(null);double bili;if(width>0){bili=width/(double)w;height = (int) (h*bili);}else{if(height>0){bili=height/(double)h;width = (int) (w*bili);}}String srcImgPath = newFile.getAbsoluteFile().toString();System.out.println(srcImgPath);String subfix = "jpg";subfix = srcImgPath.substring(stIndexOf(".")+1,srcImgPath.length());BufferedImage buffImg = null;if(subfix.equals("png")){buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);}else{buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);}Graphics2D graphics = buffImg.createGraphics();graphics.setBackground(new Color(255,255,255));graphics.setColor(new Color(255,255,255));graphics.fillRect(0, 0, width, height);graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);ImageIO.write(buffImg, subfix, new File(srcImgPath));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return newFile.getAbsolutePath();}/*** 按设置的宽度⾼度压缩图⽚⽂件<br> 先保存原⽂件,再压缩、上传* @param oldFile 要进⾏压缩的⽂件全路径* @param newFile 新⽂件* @param width 宽度* @param height ⾼度* @param quality 质量* @return 返回压缩后的⽂件的全路径*/public static String zipWidthHeightImageFile(File oldFile,File newFile, int width, int height,float quality) {if (oldFile == null) {return null;}String newImage = null;try {/** 对服务器上的临时⽂件进⾏处理 */Image srcFile = ImageIO.read(oldFile);String srcImgPath = newFile.getAbsoluteFile().toString();System.out.println(srcImgPath);String subfix = "jpg";subfix = srcImgPath.substring(stIndexOf(".")+1,srcImgPath.length());BufferedImage buffImg = null;if(subfix.equals("png")){buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);}else{buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);}Graphics2D graphics = buffImg.createGraphics();graphics.setBackground(new Color(255,255,255));graphics.setColor(new Color(255,255,255));graphics.fillRect(0, 0, width, height);graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);ImageIO.write(buffImg, subfix, new File(srcImgPath));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return newImage;}}说明:1、根据需求⼤家可以⾃⾏设置质量参数quality,到底设置成多少,可以先看下效果在取值;2、⽹上通⽤的⽅法⽤的是jdk⾃带jar包中⽅法,我这⾥衍⽣了⼀下:⽤Graphics2D,能够同时处理jpg和png格式;3、new Color(255,255,255)是⽩⾊,等同于WHITE,但是⽤WHITE 的话,Linux下某些图⽚会有其它⾊值;4、main中的宽425和⾼638可以根据⾃⼰的需求⾃⾏设置,但是对于长和宽⼀样的,按照400(⼩值的值425)*400来处理;更多java相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》及《》。
Java中图片压缩处理

Java中图⽚压缩处理整理⽂档,搜刮出⼀个Java做图⽚压缩的代码,稍微整理精简⼀下做下分享。
⾸先,要压缩的图⽚格式不能说动态图⽚,你可以使⽤bmp、png、gif等,⾄于压缩质量,可以通过BufferedImage来指定。
在C盘的temp下放置⼀张图⽚pic123.jpg,尽量找⼀个像素⾼⼀点的图⽚,这⾥我找了⼀张5616*3744的。
package test;import java.io.*;import java.util.Date;import java.awt.*;import java.awt.image.*;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.*;/*** 图⽚压缩处理* @author 崔素强*/public class ImgCompress {private Image img;private int width;private int height;@SuppressWarnings("deprecation")public static void main(String[] args) throws Exception {System.out.println("开始:" + new Date().toLocaleString());ImgCompress imgCom = new ImgCompress("C:\\temp\\pic123.jpg");imgCom.resizeFix(400, 400);System.out.println("结束:" + new Date().toLocaleString());}/*** 构造函数*/public ImgCompress(String fileName) throws IOException {File file = new File(fileName);// 读⼊⽂件img = ImageIO.read(file); // 构造Image对象width = img.getWidth(null); // 得到源图宽height = img.getHeight(null); // 得到源图长}/*** 按照宽度还是⾼度进⾏压缩* @param w int 最⼤宽度* @param h int 最⼤⾼度*/public void resizeFix(int w, int h) throws IOException {if (width / height > w / h) {resizeByWidth(w);} else {resizeByHeight(h);}}/*** 以宽度为基准,等⽐例放缩图⽚* @param w int 新宽度*/public void resizeByWidth(int w) throws IOException {int h = (int) (height * w / width);resize(w, h);}/*** 以⾼度为基准,等⽐例缩放图⽚* @param h int 新⾼度*/public void resizeByHeight(int h) throws IOException {int w = (int) (width * h / height);resize(w, h);}/*** 强制压缩/放⼤图⽚到固定的⼤⼩* @param w int 新宽度* @param h int 新⾼度*/public void resize(int w, int h) throws IOException {// SCALE_SMOOTH 的缩略算法⽣成缩略图⽚的平滑度的优先级⽐速度⾼⽣成的图⽚质量⽐较好但速度慢BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩⼩后的图File destFile = new File("C:\\temp\\456.jpg");FileOutputStream out = new FileOutputStream(destFile); // 输出到⽂件流// 可以正常实现bmp、png、gif转jpgJPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(image); // JPEG编码}}运⾏后在C盘temp下⽣成⼀个465.jpg,像素⼤⼩为600*400,像素⼤⼩是我指定的。
java等比缩小、放大图片尺寸

1<dependency> 2<groupId>net.coobird</groupId> 3<artifactId>thumbnailator</artifactId> 4<version>0.4.8</version> 5</dependency>
3.解 决 方 案
代码实现:
1 /* 2 * 对图片进行等比缩小或放大 3 * @attention: 4 * Thumbnails可以将修改后的图片转换成OutputStream、BufferedImage或者File 5 * @date: 2022/2/16 18:37 6 * @param: imgInputPath 原图片路径 7 * @param: imgOutputPath 图片输出路径 8 * 可以更改原图片的格式(比如:原图片是png格式,我们可以在让其生成的时候变成非png格式) 9 * @param: scale 图片比例 10* @return: boolean 成功、失败 11*/ 12public static boolean compressPicBySize(String imgInputPath, String imgOutputPath, float scale) { 13boolean flag = false; 14String imgStatus = (scale > 1) ? "放大" : "缩小"; 15try { 16Thumbnails.of(imgInputPath).scale(scale).toFile(imgOutputPath); 17// 成功 18flag = true; ("图片{}成功", imgStatus); 20} catch (IOException e) { 21e.printStackTrace(); 22log.error("图片{}失败:{}", imgStatus, e.getMessage()); 23} 24return flag; 25}
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
本文由我司收集整编,推荐下载,如有疑问,请与我司联系
JAVA 将任意图片文件压缩成想要的图片类型与大小2012/11/06 0 二话不说,直接贴出代码:
import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class imageTest {//测试方法public static void main(String[] args){//定义源文件File sourcefile = new File( D:\\qwe.png //定义压缩后的文件名File newFile = new File( D:\\xx.png try { imageCompress(sourcefile,newFile, 1028, 800, png } catch (IOException e) {e.printStackTrace();}}/** * 生成缩略图* @param sourceFile 源始文件路径*
@param destFile 目标文件路径* @param destWidth 目标文件宽度* @param destHeight 目标文件高度* @return flag 是否写入成功* @throws IOException
*/public static boolean imageCompress(File sourceFile, File destFile,int destWidth,int destHeight,String imageTpye) throws IOException{//保存源文件图像Image srcImage = null;//保存目标文件图像BufferedImage tagImage = null;//判断目标文件图像是否绘制
成功boolean flag = false;//判断图片文件是否存在以及是否为文件类型
if(sourceFile.exists() sourceFile.isFile()){//读取图片文件属性srcImage = ImageIO.read(sourceFile);//生成目标缩略图tagImage = new BufferedImage(destWidth,destHeight,BufferedImage.TYPE_INT_RGB);//根据目标图片
的大小绘制目标图片
tagImage.getGraphics().drawImage(srcImage,0,0,destWidth,destHeight,null);flag = ImageIO.write(tagImage, imageTpye, destFile);}else{flag = false;} return flag; }}
tips:感谢大家的阅读,本文由我司收集整编。
仅供参阅!。