Java修改图片尺寸

版权声明:转载请注名出处 https://blog.csdn.net/meism5/article/details/88525252

修改图片尺寸包括两种情况:

1、强制指定宽、高尺寸

2、按原图宽、高比例,放大或缩小

maven使用thumbnailator库依赖

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

工具代码

/**
	 * 重新生成图片宽、高
	 * @param srcPath 图片路径
	 * @param destPath 新生成的图片路径
	 * @param newWith 新的宽度
	 * @param newHeight 新的高度
	 * @param forceSize 是否强制使用指定宽、高,false:会保持原图片宽高比例约束
	 * @return
	 * @throws IOException 
	 */
	public static boolean resizeImage (String srcPath, String destPath, int newWith, int newHeight, boolean forceSize) throws IOException {
		if (forceSize) {
			Thumbnails.of(srcPath).forceSize(newWith, newHeight).toFile(destPath);
		} else {
			Thumbnails.of(srcPath).width(newWith).height(newHeight).toFile(destPath);
		}
		return true;
	}

测试代码

/**
	 * 测试重新生成图片宽、高
	 * @throws IOException 
	 */
	@Test
	public void testResizeImage() throws IOException {
		String imageName = "java_coffee.jpg";
		String srcPath = IMAGE_PATH + imageName;
		
		imageName = "java_coffee_resize.jpg";
		String destPath = IMAGE_PATH + imageName;
		boolean forceSize = true;
		Assert.assertTrue(ImageUtil.resizeImage(srcPath, destPath, 200, 200, forceSize));
	}

原图2000*1600

指定宽高强制200

 指定宽高200,非强制,修改后,得到200*160

完整源码:https://github.com/ConstXiong/xtools 

猜你喜欢

转载自blog.csdn.net/meism5/article/details/88525252
今日推荐