savePath = DEFAULT_FILE_PATH + System.currentTimeMillis() + DEFAULT_IMAGE_FORMAT;
}
FileOutputStream fos = new FileOutputStream(new File(savePath));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
encoder.encode(image);
image.flush();
fos.flush();
fos.close();
return savePath;
}
/**
* function: 可以设置图片缩放质量,并且可以根据指定的宽高缩放图片
* @author hoojo
* @createDate 2012-2-7 上午11:01:27
* @param width 缩放的宽度
* @param height 缩放的高度
* @param quality 图片压缩质量,最大值是1; 使用枚举值:{@link ImageQuality}
* Some guidelines: 0.75 high quality、0.5 medium quality、0.25 low quality
* @param savePath 保存目录
* @param targetImage 即将缩放的目标图片
* @return 图片保存路径、名称
* @throws ImageFormatException
* @throws IOException
*/
public static String resize(int width, int height, Float quality, String savePath, Image targetImage) throws ImageFormatException, IOException {
width = Math.max(width, 1);
height = Math.max(height, 1);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(targetImage, 0, 0, width, height, null);
if (savePath == null || "".equals(savePath)) {
savePath = DEFAULT_FILE_PATH + System.currentTimeMillis() + DEFAULT_IMAGE_FORMAT;
}
FileOutputStream fos = new FileOutputStream(new File(savePath));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
if (quality == null || quality <= 0) {
quality = DEFAULT_SCALE_QUALITY;
}
encodeParam.setQuality(quality, true);
encoder.encode(image, encodeParam);
image.flush();
fos.flush();
fos.close();
return savePath;
}
/**
* function: 通过指定大小和图片的大小,计算出图片缩小的合适大小
* @author hoojo
* @createDate 2012-2-6 下午05:53:10
* @param width 指定的宽度
* @param height 指定的高度
* @param image 图片文件
* @return 返回宽度、高度的int数组
*/
public static int[] getSize(int width, int height, Image image) {
int targetWidth = image.getWidth(null);
int targetHeight = image.getHeight(null);
double scaling = getScaling(targetWidth, targetHeight, width, height);
long standardWidth = Math.round(targetWidth * scaling);
long standardHeight = Math.round(targetHeight * scaling);
return new int[] { Integer.parseInt(Long.toString(standardWidth)), Integer.parseInt(String.valueOf(standardHeight)) };
}
/**
* function: 通过指定的比例和图片对象,返回一个放大或缩小的宽度、高度
* @author hoojo
* @createDate 2012-2-7 上午10:27:59
* @param scale 缩放比例
* @param image 图片对象
* @return 返回宽度、高度
*/
public static int[] getSize(float scale, Image image) {
int targetWidth = image.getWidth(null);
int targetHeight = image.getHeight(null);
long standardWidth = Math.round(targetWidth * scale);
long standardHeight = Math.round(targetHeight * scale);
return new int[] { Integer.parseInt(Long.toString(standardWidth)), Integer.parseInt(String.valueOf(standardHeight)) };
}
public st