需要写一个Image的工具类
package com.jbit.util; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.ImageIO; public class ImageUtil { /** * * @param inputStream(传入图片的输入流) * @param MaxWidth(设置图片的最大宽度) * @param imgFormat(设置图片的格式,如jpg) * @param outputStream(图片最后得到的输出流) */ public static void autoResizeImage(InputStream inputStream, int MaxWidth, String imgFormat, OutputStream outputStream) { try { if (imgFormat.startsWith(".")) { imgFormat = imgFormat.substring(1); } BufferedImage oriImg = ImageIO.read(inputStream); int o_w = oriImg.getWidth(); int o_h = oriImg.getHeight(); int width = 0; int height = 0; if (MaxWidth < o_w) { width = MaxWidth; height = (int) (o_h / (1.0 * o_w / MaxWidth)); } else { width = o_w; height = o_h; } BufferedImage desimg = createResizedCopy(oriImg, width, height); ImageIO.write(desimg, imgFormat, outputStream); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static BufferedImage createResizedCopy(Image src, int width, int height) { BufferedImage newImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = newImg.createGraphics(); g2d.setComposite(AlphaComposite.Src); g2d.drawImage(src, 0, 0, width, height, null); g2d.dispose(); return newImg; } }
package javaProject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.jbit.util.ImageUtil; public class UpdateImage { public static void main(String[] args) { try { File file=new File("e://img/7ffafa89e6.jpg"); if(file.exists()==true){ InputStream inputStream=new FileInputStream(file); ByteArrayOutputStream output=new ByteArrayOutputStream(); ImageUtil.autoResizeImage(inputStream, 100, "jpg", output); File newFile=new File("e://img/test.jpg"); if(newFile.exists()==true){ newFile.delete(); } OutputStream out=new FileOutputStream(newFile); out.write(output.toByteArray()); out.close(); }else{ System.out.println("【"+file.getPath()+"】这个路径不存在"); } } catch (Exception e) { e.printStackTrace(); } } }
转载于:https://my.oschina.net/xlyjx/blog/511216