Java修改圖片尺寸

修改圖片尺寸包括兩種情況:

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 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章