1、本文仅为了提供图片上传过程中,部分java图片处理代码。
2、以下代码可以解决部分图片上传裁剪后整体变红等失真现象。
3、以下代码支持cmyk颜色模式的图片上传裁剪。/**
*图片裁剪
*@paramsrcImageFile裁剪前图片地址
*@paramdirImageFile裁剪后图片地址
*@paramx图片裁剪属性
*@paramy图片裁剪属性
*@paramdestWidth图片裁剪属性
*@paramdestHeight图片裁剪属性
*/
publicstaticvoidabscut(StringsrcImageFile,StringdirImageFile,intx,inty,intdestWidth,intdestHeight){
BufferedImagebi=null;
try{
ImageFiltercropFilter;
Imageimg=Toolkit.getDefaultToolkit().getImage(srcImageFile);//可讀取丟失ICC信息的圖片(裁剪后图片变红等现象的原因)
bi=toBufferedImage(img);
intsrcWidth=bi.getWidth();
intsrcHeight=bi.getHeight();
if(srcWidth>=destWidth&&srcHeight>=destHeight){
Imagep_w_picpath=bi.getScaledInstance(srcWidth,srcHeight,
Image.SCALE_DEFAULT);
cropFilter=newCropImageFilter(x,y,destWidth,destHeight);
img=Toolkit.getDefaultToolkit().createImage(
newFilteredImageSource(p_w_picpath.getSource(),cropFilter));
BufferedImagetag=newBufferedImage(destWidth,destHeight,
BufferedImage.TYPE_INT_RGB);
Graphicsg=tag.getGraphics();
g.drawImage(img,0,0,null);
g.dispose();
ImageIO.write(tag,"jpg",newFile(dirImageFile));
}
}catch(Exceptione){
System.out.println("ImageUtils图片裁剪异常:"+e.getLocalizedMessage());
}
}
/**
*Image转BufferedImage
*@paramp_w_picpath
*@return
*/
publicstaticBufferedImagetoBufferedImage(Imagep_w_picpath){
if(p_w_picpathinstanceofBufferedImage){
return(BufferedImage)p_w_picpath;
}
//Thiscodeensuresthatallthepixelsinthep_w_picpathareloaded
p_w_picpath=newImageIcon(p_w_picpath).getImage();
//Determineifthep_w_picpathhastransparentpixels;forthismethod's
//implementation,seee661DeterminingIfanImageHasTransparentPixels
//booleanhasAlpha=hasAlpha(p_w_picpath);
//Createabufferedp_w_picpathwithaformatthat'scompatiblewiththescreen
BufferedImagebp_w_picpath=null;
GraphicsEnvironmentge=GraphicsEnvironment.getLocalGraphicsEnvironment();
try{
//Determinethetypeoftransparencyofthenewbufferedp_w_picpath
inttransparency=Transparency.OPAQUE;
/*if(hasAlpha){
transparency=Transparency.BITMASK;
}*/
//Createthebufferedp_w_picpath
GraphicsDevicegs=ge.getDefaultScreenDevice();
GraphicsConfigurationgc=gs.getDefaultConfiguration();
bp_w_picpath=gc.createCompatibleImage(
p_w_picpath.getWidth(null),p_w_picpath.getHeight(null),transparency);
}catch(HeadlessExceptione){
//Thesystemdoesnothaveascreen
}
if(bp_w_picpath==null){
//Createabufferedp_w_picpathusingthedefaultcolormodel
inttype=BufferedImage.TYPE_INT_RGB;
//inttype=BufferedImage.TYPE_3BYTE_BGR;//bywang
/*if(hasAlpha){
type=BufferedImage.TYPE_INT_ARGB;
}*/
bp_w_picpath=newBufferedImage(p_w_picpath.getWidth(null),p_w_picpath.getHeight(null),type);
}
//Copyp_w_picpathtobufferedp_w_picpath
Graphicsg=bp_w_picpath.createGraphics();
//Paintthep_w_picpathontothebufferedp_w_picpath
g.drawImage(p_w_picpath,0,0,null);
g.dispose();
returnbp_w_picpath;
}