java改变图片大小

/**
	 * 改变图片大小
	 * 
	 * @param filePath 原图路径
	 * @param newFilePath 新图保存路径
	 * @param size 设置的宽度
	 * @throws IOException
	 */
	private void changeSize(String filePath, String newFilePath, int size) {
		InputStream is = null;
		try {
			is = new FileInputStream(new File(filePath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		BufferedImage prevImage = null;
		try {
			prevImage = ImageIO.read(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		double width = prevImage.getWidth();
		double height = prevImage.getHeight();
		double percent = size / width;
		int newHeight = Integer.parseInt((height * percent + "").substring(0, (height * percent + "").indexOf(".")));
		System.out.println("设置的宽为" + size + "  " + "高为" + newHeight);
		try {
			Thumbnails.of(filePath).size(size, newHeight).toFile(newFilePath);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
	/**
     * 改变图片的尺寸
     *
     * @param newWidth, newHeight, path
     * @return boolean
     */
    public boolean changeSize(int newWidth, int newHeight, String path) {
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(path));

            //字节流转图片对象
            Image bi = ImageIO.read(in);
            //构建图片流
            BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            //绘制改变尺寸后的图
            tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
            //输出流
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //encoder.encode(tag);
            ImageIO.write(tag, "PNG", out);
            in.close();
            out.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }
	补充pom.xml配置中引入依赖包
	<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
		<!-- 图片处理 -->
		<dependency>
			<groupId>net.coobird</groupId>
			<artifactId>thumbnailator</artifactId>
			<version>0.4.8</version>
		</dependency>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值