画像サムネイルの実装は、比較的柔軟[直接使用可能]
2089 ワード
ここでoriginalPathはピクチャソースアドレスであり、newPathはサムネイルを生成する目的アドレスであり、newWidth、newHeightはサムネイルの幅と高さである.
// ,
public static void changeImagePixel(String originalPath,String newPath,int newWidth,int newHeight){
//
BufferedImage bi=null;
try {
bi = ImageIO.read(new File(originalPath));
// 、
int originalWidth=bi.getWidth();
int originalHeight=bi.getHeight();
// 、 , 1, 、 、
double ratio=1;
// 、 ,
double originalRatio=(double)originalWidth/originalHeight;
//
String fileType = originalPath.substring(originalPath.lastIndexOf("."));
String newFileType="jpg";
if(fileType.equals("png") || fileType.equals("PNG")){
newFileType="png";
}
//
if(originalWidth>newWidth || originalHeight>newHeight){
if(newWidth < (int)(Math.floor(newHeight * originalRatio))){
// , ,
ratio = (double)newWidth / originalWidth;
} else {
// , ,
ratio = (double)newHeight / originalHeight;
}
}
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
Image newImage = op.filter(bi, null);
try {
// ,
//File newPathDir=new File(newPath.substring(0,newPath.lastIndexOf("\\")+1));
//if(!newPathDir.exists()) newPathDir.mkdirs();
ImageIO.write((BufferedImage) newImage, newFileType, new File(newPath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}