首页 > 编程知识 正文

java片处理代码可以缩放吗,java如何自动缩放片

时间:2023-05-06 19:23:52 阅读:252064 作者:4994

java 缩放图片并输出,支持 jpg 和 png 输入及同类型输出

import java.io.File;import java.io.IOException;import java.awt.image.BufferedImage;import java.awt.Image;import java.awt.image.AffineTransformOp;import javax.imageio.ImageIO;import cn.sharcom.config.Constant;import java.awt.geom.AffineTransform; /** * * @param strDestFile * 来源文件 * @param strSourceFile * 目标文件 * @param width * 输出尺寸 width * @param height * 输出尺寸 height * @return */ public static Integer ImageZoom1(String strDestFile, String strSourceFile, int width, int height) { Integer result = null; // 打开来源文件 File fileInput = new File(strSourceFile); if (fileInput.isFile() == false) { String msg = String.format("ImageZoom no found file %s", strSourceFile); result = Constant.RESULT_NONE; return result; } // suffix 默认 jpg String strSuffix = "jpg"; // 1+ 消除 "." int point = strSourceFile.lastIndexOf(".") + 1; // 根据传入文件名获取扩展名 if (point > 0 && point < strSourceFile.length()) { int len = strSourceFile.length(); String strFileType = strSourceFile.substring(point, len); if (strFileType.length() > 0) { strFileType = strFileType.toLowerCase(); // 得到新的扩展名 strSuffix = strFileType; } } // 打开文件 File fileOutput = null; // 读取图片 BufferedImage bufferedImage = null; try { fileOutput = new File(strDestFile); bufferedImage = ImageIO.read(fileInput); } catch (IOException e) { e.printStackTrace(); String msg = String.format("ImageZoom failed to read the file. %s", strSourceFile); result = Constant.RESULT_ERROR; return result; } Image image = bufferedImage.getScaledInstance(width, height, bufferedImage.SCALE_SMOOTH); // 获取原始尺寸 int intHeightOld = bufferedImage.getHeight(); int intWidthOld = bufferedImage.getWidth(); // 计算新尺寸比例 double intWidthRatio = (double) width / (double) intWidthOld; double intHeightRatio = (double) height / (double) intHeightOld; // 设置比例 AffineTransformOp affineTransformOp = new AffineTransformOp(AffineTransform.getScaleInstance(intWidthRatio, intHeightRatio), null); image = affineTransformOp.filter(bufferedImage, null); try { // 将文件输出为指定类型 ImageIO.write((BufferedImage) image, strSuffix, fileOutput); // 设置返回标记 result = Constant.RESULT_SUCCESS; } catch (Exception e) { String msg = String.format("ImageZoom write error %s, %s", e.getMessage(), strDestFile); result = Constant.RESULT_ERROR; return result; } return result; } public static void main(String[] args) { ImageZoom1("c:/b.jpg", "c:/1239501964FE4306.jpg", 3000, 4000); }

Q群讨论:236201801


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。