Java修改图片格式

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

Java修改图片格式,支持bmp|gif|jpg|jpeg|png之间的转换

工具代码

/**
	 * 修改原图的文件格式
	 * @param srcPath 原图路径
	 * @param destPath 新图路径
	 * @param formatName 图片格式,支持bmp|gif|jpg|jpeg|png
	 * @return
	 */
	public static boolean modifyImageFormat(String srcPath, String destPath, String formatName) {
		boolean isSuccess = false;
		InputStream fis = null;
		try {
			fis = new FileInputStream(srcPath); 
			BufferedImage bufferedImg = ImageIO.read(fis);
			isSuccess = ImageIO.write(bufferedImg, formatName, new File(destPath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return isSuccess;
	}

测试代码

/**
	 * 测试修改图片格式
	 * @throws FileNotFoundException
	 */
	@Test
	public void testModifyImageFormat() throws FileNotFoundException {
		String imageName = "java_coffee.jpg";
		String srcPath = IMAGE_PATH + imageName;
		
		imageName = "java_coffee_midify.gif";
		String destPath = IMAGE_PATH + imageName;
		Assert.assertTrue(ImageUtil.modifyImageFormat(srcPath, destPath, "gif"));
		
		Assert.assertEquals(ImageUtil.getImageType(new File(destPath)),  "gif");
	}

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

猜你喜欢

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