Java画像操作
4526 ワード
1、画像圧縮
//
public static void imageCompress(String path,String newPath,String fileName,String toFileName,float scale,int width,int height){
imageCompress(path,newPath, fileName, toFileName, scale, 0.75f, width, height);
}
/**
* :
* @param path
* @param fileName
* @param toFileName
* @param scale 1, 0.5
* @param quality 0.1~1.0
* @param width
* @param height
* :void
*/
private static void imageCompress(String path,String newPath, String fileName,String toFileName,float scale,float quality,int width,int height){
FileOutputStream out = null;
try {
Image image = javax.imageio.ImageIO.read(new File(path +"/"+ fileName));
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
if(scale >=1.0) scale = 0.99f;// 0.5, , ,
//
float realscale = getRatio(imageWidth,imageHeight,width,height);
float finalScale = Math.min(scale, realscale);//
imageWidth = (int)(finalScale*imageWidth);
imageHeight = (int)(finalScale*imageHeight);
image = image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_AREA_AVERAGING);
BufferedImage mBufferedImage = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = mBufferedImage.createGraphics();
g2.drawImage(image, 0, 0,imageWidth, imageHeight, Color.white,null);
g2.dispose();
float[] kernelData2 = {-0.125f, -0.125f, -0.125f,-0.125f,2, -0.125f,-0.125f,-0.125f, -0.125f };
Kernel kernel = new Kernel(3, 3, kernelData2);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
mBufferedImage = cOp.filter(mBufferedImage, null);
out = new FileOutputStream(newPath+"/" + toFileName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(mBufferedImage);
param.setQuality(quality, true);// 0.75
encoder.setJPEGEncodeParam(param);
encoder.encode(mBufferedImage);
}catch (FileNotFoundException fnf){
fnf.printStackTrace();
}catch (IOException ioe){
ioe.printStackTrace();
}catch(Exception ex){
ex.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static float getRatio(int width,int height,int maxWidth,int maxHeight){
float Ratio = 1.0f;
float widthRatio ;
float heightRatio ;
widthRatio = (float)maxWidth/width;
heightRatio = (float)maxHeight/height;
if(widthRatio<1.0 || heightRatio<1.0){
Ratio = widthRatio<=heightRatio?widthRatio:heightRatio;
}
return Ratio;
}
/**
*
* @param map
* @return
*/
public static float getCompressSize(float width){
float result = 0.5f;
result = 595/width;
result = Float.parseFloat(StringUtil.formatNumber("#.##", result));
return result;
}
/**
* :w 、h 、s 。 null。
*
* @param imgpath
* @return map
*/
public static Map getImgInfo(InputStream fis) throws Exception {
Map map = new HashMap();
BufferedImage buff = ImageIO.read(fis);
map.put("w", new Long(buff.getWidth()* 1L)); //
//map.put("h", new Long(buff.getHeight()* 1L)); //
//map.put("s", new Long(imgfile.length())); //
fis.close();
return map;
}