首页 > 代码库 > java改变图片文件尺寸
java改变图片文件尺寸
package test.common; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.ImageIO; public class ImgTest { private Image img; private final static int WIDTH = 147; private final static int HEIGHT = 136; /** * 改变图片的大小到宽为size,然后高随着宽等比例变化 * @param is 上传的图片的输入流 * @param os 改变了图片的大小后,把图片的流输出到目标OutputStream * @param size 新图片的宽 * @param format 新图片的格式 * @throws IOException */ public static OutputStream resizeImage(InputStream is, OutputStream os, int size, String format) throws IOException { BufferedImage prevImage = ImageIO.read(is); double width = prevImage.getWidth(); double height = prevImage.getHeight(); double percent = size/width; int newWidth = (int)(width * percent); int newHeight = (int)(height * percent); BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR); Graphics graphics = image.createGraphics(); graphics.drawImage(prevImage, 0, 0, newWidth, newHeight, null); ImageIO.write(image, format, os); os.flush(); is.close(); os.close(); ByteArrayOutputStream b = (ByteArrayOutputStream) os; return os; } public static void main(String[] args) { try { InputStream is = new FileInputStream(new File("download/qrcode_test.jpg")); OutputStream os = new FileOutputStream(new File("download/qrcode_test_1.jpg")); resizeImage(is, os, 10, "png"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
java改变图片文件尺寸
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。