io获取本地图片并进行压缩然后转换base64编码
@Test
public void test5() throws Exception
{
String imgUrl
= "http://sy1.iknowmuch.com/ishelf/imgs/upload/product/debug_esl.png";
String imgdist
= "C:\\ishelf\\imgs";
String imgUrlFile
= templateCenterService
.imgUrlFile(imgdist
, imgUrl
);
File distfile
= new File(imgUrlFile
);
BufferedImage src
= ImageIO
.read(distfile
);
System
.out
.println("没压缩前大小:"+distfile
.length());
if(distfile
.length()>=3000){
int [] widthAndHeight
= new int[2];
widthAndHeight
[0] = (int)src
.getWidth(null
);
widthAndHeight
[1] = (int) src
.getHeight(null
);
reduceImg(imgUrlFile
,widthAndHeight
,(int)src
.getWidth(null
),(int) src
.getHeight(null
),null
);
System
.out
.println(distfile
.length());
}
System
.out
.println("字节码:"+getImageBinary(imgUrlFile
));
}
public static void reduceImg(String imgsrc
,int []widthAndHeight
, int widthdist
, int heightdist
, Float rate
) {
try {
File srcfile
= new File(imgsrc
);
if (!srcfile
.exists()) {
System
.out
.println("文件不存在");
}
if (rate
!= null
&& rate
> 0) {
if (widthAndHeight
== null
|| widthAndHeight
[0] == 0 || widthAndHeight
[1] == 0) {
return;
} else {
widthdist
= (int) (widthAndHeight
[0] * rate
);
heightdist
= (int) (widthAndHeight
[1] * rate
);
}
}
Image src
= ImageIO
.read(srcfile
);
BufferedImage tag
= new BufferedImage((int) widthdist
, (int) heightdist
, BufferedImage
.TYPE_INT_RGB
);
tag
.getGraphics().drawImage(src
.getScaledInstance(widthdist
, heightdist
, Image
.SCALE_SMOOTH
), 0, 0, null
);
FileOutputStream out
= new FileOutputStream(imgsrc
);
JPEGImageEncoder encoder
= JPEGCodec
.createJPEGEncoder(out
);
encoder
.encode(tag
);
out
.close();
} catch (Exception ef
) {
ef
.printStackTrace();
}
}
public static String
getImageBinary(String imageUrl
) {
String data
= null
;
try {
File imageFile
= new File(imageUrl
);
InputStream inStream
= new FileInputStream(imageFile
);
byte[] btImg
= readInputStream(inStream
);
data
= Base64
.encode(btImg
);
} catch (Exception e
) {
e
.printStackTrace();
}
return data
;
}
转载请注明原文地址: https://lol.8miu.com/read-35277.html