Java 如何改变图片大小的程序代码
Java实现图片旋转、指定图像大小和水平翻转
Java实现图⽚旋转、指定图像⼤⼩和⽔平翻转本⽂实例为⼤家分享了Java实现图⽚旋转、指定图像⼤⼩、⽔平翻转,供⼤家参考,具体内容如下package com.zeph.j2se.image;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.image.BufferedImage;public class ImageOperate {/*** 旋转图⽚为指定⾓度** @param bufferedimage* ⽬标图像* @param degree* 旋转⾓度* @return*/public static BufferedImage rotateImage(final BufferedImage bufferedimage,final int degree) {int w = bufferedimage.getWidth();int h = bufferedimage.getHeight();int type = bufferedimage.getColorModel().getTransparency();BufferedImage img;Graphics2D graphics2d;(graphics2d = (img = new BufferedImage(w, h, type)).createGraphics()).setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2);graphics2d.drawImage(bufferedimage, 0, 0, null);graphics2d.dispose();return img;}/*** 变更图像为指定⼤⼩** @param bufferedimage* ⽬标图像* @param w* 宽* @param h* ⾼* @return*/public static BufferedImage resizeImage(final BufferedImage bufferedimage,final int w, final int h) {int type = bufferedimage.getColorModel().getTransparency();BufferedImage img;Graphics2D graphics2d;(graphics2d = (img = new BufferedImage(w, h, type)).createGraphics()).setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);graphics2d.drawImage(bufferedimage, 0, 0, w, h, 0, 0,bufferedimage.getWidth(), bufferedimage.getHeight(), null);graphics2d.dispose();return img;}/*** ⽔平翻转图像** @param bufferedimage* ⽬标图像* @return*/public static BufferedImage flipImage(final BufferedImage bufferedimage) {int w = bufferedimage.getWidth();int h = bufferedimage.getHeight();BufferedImage img;Graphics2D graphics2d;(graphics2d = (img = new BufferedImage(w, h, bufferedimage.getColorModel().getTransparency())).createGraphics()).drawImage(bufferedimage, 0, 0, w, h, w, 0, 0, h, null);graphics2d.dispose();return img;}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
Java开源工具Jimi处理图片大小及格式转换
double height = (double) src.getHeight(null); // 得到源图长
System.out.println("源图宽:"+wideth);
String temp = desc;
File _file = null;
if (desc == null || desc.trim().equals(""))
desc = source;
if (!desc.toLowerCase().trim().endsWith("jpg")) {
writer.setSource(image);
// 加入属性设置,非必要
// /*
writer.setOptions(options);
// */
writer.putImage(outfile);
} catch (JimiException je) {
* @param quality
* 图片格式转换
*/
public void toJPG(String source, String type, int quality) {
//0<quality<100
if (quality < 0 || quality > 100 || (quality + "") == null || (quality + "").equals("")) {
Java开源工具Jimi处理图片大小及格式转换
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图⽚压缩到指定⼤⼩这是压缩到⼩于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实现上传图⽚尺⼨修改和质量压缩的具体代码,供⼤家参考,具体内容如下package com.zity.frame.util;/*** 缩略图实现,将图⽚(jpg、bmp、png、gif等等)真实的变成想要的⼤⼩*/import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;import net.sourceforge.pinyin4j.PinyinHelper;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.*;import .MalformedURLException;import .URL;import .URLConnection;import java.util.Random;/******************************************************************************** 缩略图类(通⽤)本java类能将jpg、bmp、png、gif图⽚⽂件,进⾏等⽐或⾮等⽐的⼤⼩转换。
具体使⽤⽅法* compressPic(⼤图⽚路径,⽣成⼩图⽚路径,⼤图⽚⽂件名,⽣成⼩图⽚⽂名,⽣成⼩图⽚宽度,⽣成⼩图⽚⾼度,是否等⽐缩放(默认为true))*/public class CompressPic {private File file = null; // ⽂件对象private String inputDir; // 输⼊图路径private String outputDir; // 输出图路径private String inputFileName; // 输⼊图⽂件名private String outputFileName; // 输出图⽂件名private int outputWidth = 300; // 默认输出图⽚宽private int outputHeight = 150; // 默认输出图⽚⾼private boolean proportion = true; // 是否等⽐缩放标记(默认为等⽐缩放)public CompressPic() { // 初始化变量inputDir = "";outputDir = "";inputFileName = "";outputFileName = "";outputWidth = 300;outputHeight = 150;}public void setInputDir(String inputDir) {this.inputDir = inputDir;}public void setOutputDir(String outputDir) {this.outputDir = outputDir;}public void setInputFileName(String inputFileName) {this.inputFileName = inputFileName;}public void setOutputFileName(String outputFileName) {this.outputFileName = outputFileName;}public void setOutputWidth(int outputWidth) {this.outputWidth = outputWidth;}public void setOutputHeight(int outputHeight) {this.outputHeight = outputHeight;}public void setWidthAndHeight(int width, int height) {this.outputWidth = width;this.outputHeight = height;}/** 获得图⽚⼤⼩* 传⼊参数 String path :图⽚路径*/public long getPicSize(String path) {file = new File(path);return file.length();}/*** 图⽚处理* @return*/public String compressPic() {try {//获得源⽂件file = new File(inputDir + inputFileName);if (!file.exists()) {return "";}// ⽣成存储路径File outDir = new File(outputDir);if(!outDir.exists()){outDir.mkdirs();}Image img = ImageIO.read(file);// 判断图⽚格式是否正确if(img==null){return "";}if (img.getWidth(null) == -1) {System.out.println(" can't read,retry!" + "<BR>");return "no";} else {int newWidth; int newHeight;// 判断是否是等⽐缩放if (this.proportion == true) {// 为等⽐缩放计算输出的图⽚宽度及⾼度int w =img.getWidth(null);int h = img.getHeight(null);//如果图⽚的宽度⼩于等于250,并且⾼度⼩于等于183,图⽚原样输出if(w<=300){outputWidth=w;}if(h<=150){outputHeight=h;}double rate1 = ((double) img.getWidth(null)) / (double) outputWidth;double rate2 = ((double) img.getHeight(null)) / (double) outputHeight;// 根据缩放⽐率⼤的进⾏缩放控制// double rate = rate1 > rate2 ? rate1 : rate2;// 保证宽度为250pxdouble rate = rate1;newWidth = (int) (((double) img.getWidth(null)) / rate);newHeight = (int) (((double) img.getHeight(null)) / rate2);} else {newWidth = outputWidth; // 输出的图⽚宽度newHeight = outputHeight; // 输出的图⽚⾼度}//重新设置⾼宽为图⽚真实⾼宽,上⾯的⾼宽是其他项⽬需要300*150的,我没得空删掉newWidth = getImgWidth(file);newHeight = getImgHeight(file);BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);/** Image.SCALE_SMOOTH 的缩略算法⽣成缩略图⽚的平滑度的* 优先级⽐速度⾼⽣成的图⽚质量⽐较好但速度慢*/tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); FileOutputStream out = new FileOutputStream(outputDir + outputFileName);// JPEGImageEncoder可适⽤于其他图⽚类型的转换JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(tag);out.close();}} catch (IOException ex) {ex.printStackTrace();}return "ok";}/*** 图⽚处理⼊⼝* @param inputDir 输⼊图路径* @param outputDir 输出图路径* @param inputFileName 输⼊图名* @param outputFileName 输出图名* @return*/public String compressPic (String inputDir, String outputDir, String inputFileName, String outputFileName) {// 输⼊图路径this.inputDir = inputDir;// 输出图路径this.outputDir = outputDir;// 输⼊图⽂件名this.inputFileName = inputFileName;// 输出图⽂件名this.outputFileName = outputFileName;return compressPic();}/*** 图⽚处理⼊⼝* @param inputDir 输⼊图路径* @param outputDir 输出图路径* @param inputFileName 输⼊图名* @param outputFileName 输出图名* @param width 输出图宽度* @param height 输⼊图宽度* @param gp 等⽐缩放* @return*/public String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName, int width, int height, boolean gp) { // 输⼊图路径this.inputDir = inputDir;// 输出图路径this.outputDir = outputDir;// 输⼊图⽂件名this.inputFileName = inputFileName;// 输出图⽂件名this.outputFileName = outputFileName;// 设置图⽚长宽setWidthAndHeight(width, height);// 是否是等⽐缩放标记this.proportion = gp;return compressPic();}/*** 图⽚压缩* @param downloadUrl* @param inputDir* @param outDir* @return*/public String ImageCompression(String downloadUrl,String inputDir,String outDir){Random rnd = new Random();String picName = downloadUrl.substring(stIndexOf("/")+1);String extendName ="";String beforeName= "";if(picName.contains(".")){extendName = picName.substring(picName.indexOf("."));beforeName= picName.substring(0,picName.indexOf("."));}else{extendName = picName;beforeName= picName;}//随机数Integer r = rnd.nextInt(1000);beforeName = new CompressPic().getPinYinHeadChar(beforeName);long ts = System.currentTimeMillis();String outpicName=ts+beforeName+r+".jpg";outpicName = outpicName.replace("%", "");if(outpicName.contains("张栋杰总经理会见旭阳集团董事长杨雪岗")){outpicName="zdjzjlhjxyjtdszyxg.jpg";}if(httpDownload(downloadUrl, inputDir, outpicName)){// 当前时间// String curTime = new Long(System.currentTimeMillis()).toString();pressPic(inputDir, outDir, outpicName, outpicName, 300, 150, true);return outpicName;}else {return null;}}/*** http图⽚下载* @param httpUrl* @param saveFile* @return*/public static boolean httpDownload(String httpUrl,String saveDir,String saveName){// 下载⽹络⽂件int bytesum = 0;int byteread = 0;URL url = null;try {url = new URL(httpUrl);} catch (MalformedURLException e1) {e1.printStackTrace();return false;}// 存储⽬录File outDir = new File(saveDir);if(!outDir.exists()){outDir.mkdirs();}try {URLConnection conn = url.openConnection();InputStream inStream = conn.getInputStream();FileOutputStream fs = new FileOutputStream(saveDir+saveName);byte[] buffer = new byte[1204];while ((byteread = inStream.read(buffer)) != -1) {bytesum += byteread;fs.write(buffer, 0, byteread);}fs.close();inStream.close();} catch (FileNotFoundException e) {e.printStackTrace();return false;} catch (IOException e) {e.printStackTrace();return false;}return true;}/*** 提取每个汉字的⾸字母** @param str* @return String*/public String getPinYinHeadChar(String str) {String convert = "";for (int j = 0; j < str.length(); j++) {char word = str.charAt(j);// 提取汉字的⾸字母String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);if (pinyinArray != null) {convert += pinyinArray[0].charAt(0);} else {convert += word;}}return convert;}public static void main(String[] arg) {CompressPic mypic = new CompressPic();pressPic("C:\\Users\\mazhaoxu\\Desktop\\", "C:\\Users\\mazhaoxu\\Desktop\\", "微信图⽚_20180712182800.png", "2019061818542824511111111111.png");// if(httpDownload("http://221.195.72.44:8122/NR/rdonlyres/B5071DE7-9652-44AF-9534-0EE0ED2DCA92/15177/resource_651768621.jpg", "D:\\data\\resource_651768621.jpg")){ // int start = (int) System.currentTimeMillis(); // 开始时间// pressPic("D:\\data\\", "D:\\data\\", "resource_651768621.jpg", "r1"+start+".jpg", 250, 250, true);// }// String s= mypic.getPinYinHeadChar("http://114.251.186.42:81/web-s/images/1447069462915xfydh1_fb_fb521.jpg");// mypic.ImageCompression("http://114.251.186.42:81/web-s/images/mobile/1447069462915xfydh1_fb_fb521.jpg","d:\\images\\", "d:\\images\\mobile\\");// pressPic("d:\\", "d:\\image\\mobile", "144921941137520151204fgw1747.jpg", "144921941137520151204fgw1747.jpg");// String s = "/image/dslfsjss/image/sisis /image";// System.out.println(s.replace("/image/", "/mobile/image/"));}/*** 获取图⽚宽度* @param file 图⽚⽂件* @return 宽度*/public static int getImgWidth(File file) {InputStream is = null;BufferedImage src = null;int ret = -1;try {is = new FileInputStream(file);src = javax.imageio.ImageIO.read(is);ret = src.getWidth(null); // 得到源图宽is.close();} catch (Exception e) {e.printStackTrace();}return ret;}/*** 获取图⽚⾼度* @param file 图⽚⽂件* @return ⾼度*/public static int getImgHeight(File file) {InputStream is = null;BufferedImage src = null;int ret = -1;try {is = new FileInputStream(file);src = javax.imageio.ImageIO.read(is);ret = src.getHeight(null); // 得到源图⾼is.close();} catch (Exception e) {e.printStackTrace();}return ret;}}这是我⽤的⼯具类,其中⾥⾯业务会⽤到pinyin4j的jar包,和图⽚压缩关系不⼤,可以去除,我是因为⽐较着急改完,就没动,如果不想改,需要引⼊pinyin4j的jar包。
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}
JAVA将任意图片文件压缩成想要的图片类型与大小
本文由我司收集整编,推荐下载,如有疑问,请与我司联系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:感谢大家的阅读,本文由我司收集整编。
getscaledinstance的用法
getscaledinstance方法的用法getscaledinstance是Java中Image类的一个方法,用于获取按比例缩放后的图像实例。
该方法可以根据指定的宽度和高度,自动调整图像的大小,保持原始图像的宽高比。
方法原型public static Image getScaledInstance(Image img, int width, int height, int hi nts)参数说明•img:要缩放的图像实例。
•width:目标图像的宽度。
•height:目标图像的高度。
•hints:缩放算法选项,可选值有:–Image.SCALE_DEFAULT:默认缩放算法。
–Image.SCALE_FAST:速度较快但质量较低的缩放算法。
–Image.SCALE_SMOOTH:速度较慢但质量较高的缩放算法。
–Image.SCALE_REPLICATE:使用复制像素的方式进行缩放。
–Image.SCALE_AREA_AVERAGING:使用平均区域值进行缩放。
返回值返回按比例缩放后的新图像实例。
使用示例下面是一个使用getscaledinstance方法进行图片缩放的示例代码:import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class ImageScaler {public static void main(String[] args) {try {// 读取原始图像BufferedImage originalImage = ImageIO.read(new File("original.jpg "));// 调整图像大小int newWidth = 200;int newHeight = 200;Image scaledImage = originalImage.getScaledInstance(newWidth, newH eight, Image.SCALE_SMOOTH);// 创建缩放后的新图像实例BufferedImage scaledBufferedImage = new BufferedImage(newWidth, ne wHeight, BufferedImage.TYPE_INT_RGB);Graphics2D graphics2D = scaledBufferedImage.createGraphics();graphics2D.drawImage(scaledImage, 0, 0, null);graphics2D.dispose();// 将缩放后的图像保存到文件ImageIO.write(scaledBufferedImage, "jpg", new File("scaled.jpg")); } catch (IOException e) {e.printStackTrace();}}}在上述示例中,我们首先使用ImageIO.read方法读取原始图像文件,并将其存储在BufferedImage对象中。
java 中处理图片的操作
BufferedImage b1;
BufferedImage biSrc = new BufferedImage(orgImage.getIconWidth(), orgImage.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
// biSrc.getGraphics().setColor(Color.white);
{ 0.0f, 0.0f, 1.0f, 0.0f } ,
{ 0.0f, 0.0f, 1.0f, 0.0f }
};
public static ImageIcon ColorImage(ImageIcon orgImage, int alarmStatus )
{
float[][] targetMatrix ;
{ 0.0f, 0.0f, 0.0f, 0.0f } ,
{ 1.0f, 1.0f, 0.0f, 0.0f }
};
static final float WARNING_BAND_MATRIX[][] =
{
{ቤተ መጻሕፍቲ ባይዱ0.5f, 0.0f, 0.0f , 0.0f},
{ 0.0f, 0.0f, 0.0f , 0.0f},
case CommonConstants.ALARM_MINOR: targetMatrix = MINOR_BAND_MATRIX; break;
case CommonConstants.ALARM_MAJOR: targetMatrix = MAJOR_BAND_MATRIX; break;
{
BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Java 图像缩放
}
//按钮事件处理类
class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
chooser.setCurrentDirectory(new File(".")); //设置文件选择器当前目录
//设置图像文件过滤器
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File file) { //可接受的文件类型
}
public String getDescription() {return "图像文件"; //文件描述}
});
int result = chooser.showOpenDialog(this); //显示文件选择对话框
if (result == JFileChooser.APPROVE_OPTION) { //得到用户行为
}
//使用文件选择器载入图像
public void fileSelect() {
JFileChooser chooser = new JFileChooser(); //实例化文件选择器
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//模式为仅打开文件
private JButton jbFile = new JButton("打开图像文件"); //打开图像文件按钮
图片大小操作
1、用鼠标拖动来改变大小以下是代码片段:<S C R I P T LA N G U A GE="J a v a S c r i p t">f u n c t i o n r e s iz e I mag e(e v t,o b j){n e wX=e v t.xn e wY=e v t.yo b j.w i d th=n e wXo b j.h e i g h t=n e wY}</s c r ip t><i mg s r c="7s a y.g i f"o n d r a g="r e s iz e I ma g e(e v e n t,th i s)">2、用鼠标滚动控制图片大小以下是代码片段:<i mg s r c="7s a y.g i f"o n mo u s e e n t e r="f o c u s();"o n mo u s e o u t="b lu r();" o n mo u s e wh e e l="w i d th+=(w i n d o w.e v e n t.w h e e lD e l t a==120)?-5:+5;">3、图片标签里用代码控制大小以下是代码片段:<i mg b o r d e r="0" s r c="[!--p i c u r l--]" o n lo a d="i f(t h is.w id th>s c r e e n.w id t h-500)th is.s t yl e.w i d th=s c r e e n.w i d t h-50 0;">4、C S S控制图片大小1.c s s2直接实现: i mg{ma x-w i d th:500p x;}(I E暂不支持)2.e x p r e s s io n实现: i mg{w i d th:e x p r e s s io n(wi d th>500?"500p x":w i d t h);}(I E o n l y)3.使用j s.方法: 用d o c u me n t.g e tE le me n t s B yTa g N a me("I M G")的方法取得全部i mg元素遍历i mg元素判断其宽度并做相应操作。
Java将大图片转成小图片
我们经常会将一个小的图片变成小一些的图片,利用java可以方便的实现,而且实现了这个功能后就可以实现更强大的功能,将一个文件夹中的所有图片都变成一个尺寸。
这里提供一个将大图变成小图的方法。
并且提供一个根据这个方法的写好的一个:图片批量尺寸处理器。
可以将一个文件夹下的所有图片,批量的按照一定尺寸都保存到另一个文件夹中。
该工具在操作超大图片的时候会出现内存溢出的错误。
功能简单也没有做太多出错处理,一般情况下挺好用的,大家将就着用吧。
import java.awt.Graphics2D;import java.awt.Image;import java.awt.geom.AffineTransform;import java.awt.image.AffineTransformOp;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import javax.imageio.ImageIO;public class Temp01{private Temp01(){}private void imageOp(InputStream inFile, String outFilePath, int width, int height){Image image = null;try {image = ImageIO.read(inFile);} catch (IOException e) {System.out.println("file path error...");}int originalImageWidth = image.getWidth(null);int originalImageHeight = image.getHeight(null);BufferedImage originalImage = new BufferedImage( originalImageWidth,originalImageHeight,BufferedImage.TYPE_3BYTE_BGR);Graphics2D g2d = originalImage.createGraphics();g2d.drawImage(image, 0, 0, null);BufferedImage changedImage =new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);double widthBo = (double)width/originalImageWidth;double heightBo = (double)width/originalImageHeight; AffineTransform transform = new AffineTransform();transform.setToScale(widthBo, heightBo);AffineTransformOp ato = new AffineTransformOp(transform, null);ato.filter(originalImage, changedImage);File fo = new File(outFilePath); //将要转换出的小图文件try {ImageIO.write(changedImage, "jpeg", fo);} catch (Exception e) {e.printStackTrace();}}private void imageOp(String inFilePath, String outFilePath, int width, int height){File tempFile = new File(inFilePath);Image image = null;try {image = ImageIO.read(tempFile);} catch (IOException e) {System.out.println("file path error...");}int originalImageWidth = image.getWidth(null);int originalImageHeight = image.getHeight(null);BufferedImage originalImage = new BufferedImage(originalImageWidth,originalImageHeight,BufferedImage.TYPE_3BYTE_BGR);Graphics2D g2d = originalImage.createGraphics();g2d.drawImage(image, 0, 0, null);BufferedImage changedImage =new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);double widthBo = (double)width/originalImageWidth;double heightBo = (double)width/originalImageHeight;AffineTransform transform = new AffineTransform();transform.setToScale(widthBo, heightBo);AffineTransformOp ato = new AffineTransformOp(transform, null);ato.filter(originalImage, changedImage);File fo = new File(outFilePath); //将要转换出的小图文件try {ImageIO.write(changedImage, "jpeg", fo);} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) throws FileNotFoundException { Temp01 t1 = new Temp01();t1.imageOp("C:/p02.jpg", "C:/p03.jpg", 400, 300);InputStream in = new FileInputStream(new File("C:/p02.jpg")); t1.imageOp(in, "C:/p04.jpg", 400, 300);}}。
Java实现图片压缩代码,图片大小转换
Java实现图⽚压缩代码,图⽚⼤⼩转换在很多项⽬中我们会把上传的图⽚做处理,⽐较图⽚上传过多对服务器的容量和带宽有很多的浪费,如果不是必须的⾼清图⽚,我们可以通过代码来做压缩。
在我的项⽬中我们压缩图⽚的⽬的是让web页⾯打开的速度很快,并且节省空间。
下⾯先分享⼀下代码:package org.util;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.awt.image.CropImageFilter;import java.awt.image.FilteredImageSource;import java.awt.image.ImageFilter;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;public class ImgTools {/*** 按照宽⾼⽐例压缩** @param img* @param width* @param height* @param out* @throws IOException*/public static void thumbnail_w_h(File img, int width, int height,OutputStream out) throws IOException {BufferedImage bi = ImageIO.read(img);double srcWidth = bi.getWidth(); // 源图宽度double srcHeight = bi.getHeight(); // 源图⾼度double scale = 1;if (width > 0) {scale = width / srcWidth;}if (height > 0) {scale = height / srcHeight;}if (width > 0 && height > 0) {scale = height / srcHeight < width / srcWidth ? height / srcHeight: width / srcWidth;}thumbnail(img, (int) (srcWidth * scale), (int) (srcHeight * scale), out);}/*** 按照固定宽⾼原图压缩** @param img* @param width* @param height* @param out* @throws IOException*/public static void thumbnail(File img, int width, int height,OutputStream out) throws IOException {BufferedImage BI = ImageIO.read(img);Image image = BI.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.setColor(Color.RED);g.drawImage(image, 0, 0, null); // 绘制处理后的图g.dispose();ImageIO.write(tag, "JPEG", out);}/*** 按照宽⾼裁剪** @param srcImageFile* @param destWidth* @param destHeight* @param out*/public static void cut_w_h(File srcImageFile, int destWidth,int destHeight, OutputStream out) {cut_w_h(srcImageFile, 0, 0, destWidth, destHeight, out);}public static void cut_w_h(File srcImageFile, int x, int y, int destWidth,int destHeight, OutputStream out) {try {Image img;ImageFilter cropFilter;// 读取源图像BufferedImage bi = ImageIO.read(srcImageFile);int srcWidth = bi.getWidth(); // 源图宽度int srcHeight = bi.getHeight(); // 源图⾼度if (srcWidth >= destWidth && srcHeight >= destHeight) {Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);cropFilter = new CropImageFilter(x, y, destWidth, destHeight);img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));BufferedImage tag = new BufferedImage(destWidth, destHeight,BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(img, 0, 0, null); // 绘制截取后的图g.dispose();// 输出为⽂件ImageIO.write(tag, "JPEG", out);}} catch (Exception e) {e.printStackTrace();}}// #cut_w_hpublic static void main(String[] args) throws IOException {File img = new File("e:\\a\\a.jpg");FileOutputStream fos = new FileOutputStream("e:\\a\\b.jpg");// ImgTools.thumbnail(img, 100, 100, fos);// ImgTools.cut_w_h(img, 230, 200, fos);ImgTools.thumbnail_w_h(img, 100, 0, fos);}}其实我们很多⼈喜欢在上传的时候就做了限制了,这样在上传时就节省了带宽,可是很多客户是不会做图⽚处理的,5M的⼤图直接就给你上传,限制了说我们做的不⼈性化。
getscaledinstance的用法
getscaledinstance的用法Java中的"getScaledInstance"方法是一个非常有用的方法。
它可以用来调整图像的大小和比例。
在这里,我将向您介绍getScaledInstance方法的用法。
getScaledInstance的使用方法如下:BufferedImage scaledImage =originalImage.getScaledInstance(width, height,Image.SCALE_SMOOTH);其中“originalImage”是原始的BufferedImage对象,“width”和“height”是新图像的宽度和高度,“Image.SCALE_SMOOTH”是调整图像大小的方式。
在这个例子中,我们使用了“SCALE_SMOOTH”以确保图像在调整大小时保持平滑。
您也可以使用其他值,如“SCALE_FAST”或“SCALE_REPLICATE”。
值得注意的是,此方法返回的是Image对象,而不是BufferedImage 对象。
因此,我们需要将其转换为BufferedImage对象才能进行其他处理。
以下是一个完整的示例代码:BufferedImage originalImage = ImageIO.read(newFile("original.png"));int width = 500; // 新宽度int height = 500; // 新高度BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);Graphics2D graphics2D = scaledImage.createGraphics();graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATI ON, RenderingHints.VALUE_INTERPOLATION_BILINEAR);graphics2D.drawImage(originalImage, 0, 0, width, height, null); graphics2D.dispose();在这个例子中,我们首先使用ImageIO来读取原始图像。
java实现图片分割指定大小
java实现图⽚分割指定⼤⼩本⽂实例为⼤家分享了java实现图⽚分割指定⼤⼩的具体代码,供⼤家参考,具体内容如下1.使⽤⼯具:ThumbnailsThumbnails 是由⾕歌提供的图⽚处理包,⽬前版本0.4.8。
可以简洁的实现图⽚的缩放、压缩、旋转、⽔印、格式转换等操作。
2.引⼊maven<dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency>//最新版本可⾃查3.⼯具类import org.springframework.web.multipart.MultipartFile;import net.coobird.thumbnailator.Thumbnails;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;/*** @Auther: lch* @Date: 2019/3/11 09:58* @Description: 图⽚⼯具类*/public class ImgUtils {public static byte[] uploadImg(Integer height,Integer width,MultipartFile file) throws Exception{String fileSuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);BufferedImage bufferedImageBig = Thumbnails.of(file.getInputStream()).forceSize(height, width).asBufferedImage();//⼤图字节转换ByteArrayOutputStream outBig = new ByteArrayOutputStream();try {ImageIO.write(bufferedImageBig, fileSuffix, outBig);} catch (IOException e) {e.printStackTrace();}return outBig.toByteArray();}}4.切割图⽚返回字节数组/*** 接收⽂件*** @param model* @return* @throws IOException* @throws IllegalStateException*/@RequestMapping(value = "imageupload")public void imageUpload(MultipartFile file) throws IllegalStateException, IOException {//⽂件名称String realFileName = file.getOriginalFilename();//⽂件后缀String suffix = realFileName.substring(stIndexOf(".") + 1);/***************⽂件处理*********************/try {//⼤图图⽚切割 --宽⾼ 720 - 720byte[] bytesBig = ImgUtils.uploadImg(720, 720, file);//中图图⽚切割 --宽⾼ 200 - 200byte[] bytesMiddle = ImgUtils.uploadImg(200, 200, file);//⼩图图⽚切割 --宽⾼ 50- 50byte[] bytesSmall = ImgUtils.uploadImg(50, 50, file);/************以上三种byte数组,即为切割后的⽂件******************/} catch (Exception e) {System.out.println("错误");}}⼩编再为⼤家补充⼀段相关代码:java图⽚切割圆形@Testpublic void test() {try {// 读取图⽚BufferedImage bi1 = ImageIO.read(new File("g:/free-sheet-share.jpg"));BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(),BufferedImage.TYPE_INT_RGB);Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());Graphics2D g2 = bi2.createGraphics();g2.setBackground(Color.WHITE);g2.fill(new Rectangle(bi2.getWidth(), bi2.getHeight()));g2.setClip(shape);//设置抗锯齿g2.drawImage(bi1, 0, 0, null);g2.dispose();ImageIO.write(bi2, "jpg", new File("e:/2.jpg"));} catch (IOException e) {e.printStackTrace();}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
用java处理图片大小
用java处理图片大小(转)import java.awt.Image;import java.awt.geom.AffineTransform;import java.awt.image.AffineTransformOp;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileFilter;import javax.imageio.ImageIO;import javax.swing.Icon;import javax.swing.ImageIcon;public class WriterImage implements FileFilter{public boolean accept(File pathname){boolean acc=false;String temp=pathname.getName();temp=temp.toLowerCase();if(temp.endsWith(".jpg")||temp.endsWith(".jpeg")){if(pathname.length()<(1024*1024))acc=true;}return acc;}public static Icon getFixedBoundIcon(String filePath, String toPath, int height, int width) throws Exception{double ratio = 0.0;// 缩放比例File F = new File(filePath);if (!F.isFile())throw new Exception(F+ " is not image file error in getFixedBoundIcon!"); Icon ret = new ImageIcon(filePath);BufferedImage Bi = ImageIO.read(F);if ((Bi.getHeight() > height) || (Bi.getWidth() > width)){if (Bi.getHeight() > Bi.getWidth()){ratio = (new Integer(height)).doubleValue() /Bi.getHeight();} else{ratio = (new Integer(width)).doubleValue() /Bi.getWidth();System.out.println("ratio" + ratio);}} else{ratio = 1.0;System.out.println("ratio" + ratio);}File ThF = new File(toPath);Image Itemp = Bi.getScaledInstance(width, height,Bi.SCALE_SMOOTH);AffineTransformOp op = new AffineTransformOp(AffineTransform .getScaleInstance(ratio, ratio), null);Itemp = op.filter(Bi, null);try{ImageIO.write((BufferedImage) Itemp, "jpg", ThF);ret = new ImageIcon(ThF.getPath());} catch (Exception e){e.printStackTrace();}return ret;}}。
Java操作图片改变大小加水印
Java操作图片改变大小加水印import java.awt.*;import java.awt.image.*;import javax.imageio.ImageIO;import javax.imageio.ImageIO.*;import javax.imageio.IIOException;import java.io.*;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;import javax.servlet.http.HttpSession;// 图片操作,改变大小加水印***********@与羊共舞的狼public class ImageOperate {public void waterMark(String strOriginalFileName,String strWaterMarkFileName,HttpSession session){try{//源文件String root=session.getServletContext().getRealPath("/");File fileOriginal = new File(root+strOriginalFileName);Image imageOriginal = ImageIO.read(fileOriginal);int widthOriginal = imageOriginal.getWidth(null);int heightOriginal = imageOriginal.getHeight(null);System.out.println("widthOriginal:" + widthOriginal + "theightOriginal:" + heightOriginal);BufferedImage bufImage = newBufferedImage(widthOriginal,heightOriginal,BufferedImage. TYPE_INT_RGB );Graphics g = bufImage.createGraphics();g.drawImage(imageOriginal,0,0,widthOriginal,heightOrigina l,null);//水印文件File fileWaterMark = new File(root+strWaterMarkFileName);Image imageWaterMark = ImageIO.read(fileWaterMark);int widthWaterMark = imageWaterMark.getWidth(null);int heightWaterMark = imageWaterMark.getHeight(null);System.out.println("widthWaterMark:" + widthWaterMark + "theightWaterMark:" + heightWaterMark);//水印文件在源文件的右下角g.drawImage(imageWaterMark,widthOriginal -widthWaterMark,heightOriginal -heightWaterMark,widthWaterMark,heightWaterMark,null);g.dispose();FileOutputStream fos = new FileOutputStream( root+strOriginalFileName); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos); encoder.encode(bufImage);fos.flush();fos.close();fos = null;}catch(Exception e){e.printStackTrace();}}public void alterSize(String srcImgFile,String addChar,int new_w,int new_h,HttpSession session){//System.out.print("文件路径为:"+"//"+srcImgFile);String root=session.getServletContext().getRealPath("/");java.io.File file=new java.io.File(root+srcImgFile);if(file.exists())System.out.println("文件存在");elseSystem.out.println("文件不存在");int i = srcImgFile.indexOf(".");int sLen = srcImgFile.length();String suffix = srcImgFile.substring(i, sLen); //带点+后缀名String urlName=srcImgFile.substring(0,i); //路径+文件名String newUrlName=root+urlName+addChar+suffix;//System.out.print("新文件名为"+newUrlName);Image src=null;try{src = javax.imageio.ImageIO.read(file);java.awt.image.BufferedImage tag = newjava.awt.image.BufferedImage(new_w,new_h,java.awt.image. BufferedImage .TYPE_INT_RGB);tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); FileOutputStream newimage=new FileOutputStream(newUrlName); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);encoder.encode(tag); //近JPEG编码newimage.close();}catch(IIOException ee){ee.printStackTrace();System.out.print("这里出错了"); }catch(Exception e){e.printStackTrace();}}//End sizeAlter }。
Java如何改变图片大小的程序代码
Java如何改变图片大小的程序代码Java 如何改变图片大小的程序代码前面在做项目的时候,有一个需求是需要上传图片的,然而该图片只是简单的展示一些信息,不需要很大,所以在上传图片的时候改变图片的大小就显得很有必要了!然后就写了下面这个方法来改变图片的大小!Java代码1. /**2. * 改变图片的大小到宽为size,然后高随着宽等比例变化3. * @param is 上传的图片的输入流4. * @param os 改变了图片的大小后,把图片的流输出到目标OutputStream5. * @param size 新图片的宽6. * @param format 新图片的格式7. * @throws IOException8. */9. public static void resizeImage(InputStream is, OutputStream os, int size, String format) throws IOException {10. BufferedImage prevImage = ImageIO.read(is);11. double width = prevImage.getWidth();12. double height = prevImage.getHeight();13. double percent = size/width;14. int newWidth = (int)(width * percent);15. int newHeight = (int)(height * percent);16. BufferedImage image = new BufferedImage(newWidth, newHeight,BufferedImage.TYPE_INT_BGR);17. Graphics graphics = image.createGraphics();18. graphics.drawImage(prevImage, 0, 0, newWidth,newHeight, null);19. ImageIO.write(image, format, os);20. os.flush();21. is.close();22. os.close();23. }。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Java 如何改变图片大小的程序代码
前面在做项目的时候,有一个需求是需要上传图片的,然而该图片只是简单的展示一些信息,不需要很大,所以在上传图片的时候改变图片的大小就显得很有必要了!然后就写了下面这个方法来改变图片的大小!
Java代码
1. /**
2. * 改变图片的大小到宽为size,然后高随着宽等比例变化
3. * @param is 上传的图片的输入流
4. * @param os 改变了图片的大小后,把图片的流输出到目标OutputStream
5. * @param size 新图片的宽
6. * @param format 新图片的格式
7. * @throws IOException
8. */
9. public static void resizeImage(InputStream is, OutputStream os, int size, String format) throws IOException {
10. BufferedImage prevImage = ImageIO.read(is);
11. double width = prevImage.getWidth();
12. double height = prevImage.getHeight();
13. double percent = size/width;
14. int newWidth = (int)(width * percent);
15. int newHeight = (int)(height * percent);
16. BufferedImage image = new BufferedImage(newWidth, newHeight,
BufferedImage.TYPE_INT_BGR);
17. Graphics graphics = image.createGraphics();
18. graphics.drawImage(prevImage, 0, 0, newWidth, newHeight, null);
19. ImageIO.write(image, format, os);
20. os.flush();
21. is.close();
22. os.close();
23. }。