public String getPic2(String imageUrl, String fileNamePath) {
Image img = null;
URL url;
// url请求图片流
DataInputStream dis = null;
// 文件写入流
InputStream in = null;
byte[] data = null;
try {
url = new URL(imageUrl);
dis = new DataInputStream(url.openStream());
// 读取图片流
img = ImageIO.read(dis);
int newWidth;
int newHeight;
// 输出图片计划尺寸,这决定最后缩放比例
int outWidthSize = 1800;
int outHeightSize = 1800;
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null))
/ (double) outWidthSize + 0.1;
double rate2 = ((double) img.getHeight(null))
/ (double) outHeightSize + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);
/*
* * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 * 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(fileNamePath);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// 将缩放后图片画到指定文件
encoder.encode(tag);
// 转换后的图片加载,供转码用
in = new FileInputStream(fileNamePath);
data = new byte[in.available()];
in.read(data);
in.close();
dis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println("图片不存在!");
return "";
}
// 图片转码
BASE64Encoder encoder = new BASE64Encoder();
String strUTF8=encoder.encode(data);
try {
strUTF8=URLEncoder.encode(strUTF8, "UTF-8");
System.out.println("++转码成功++");
} catch (UnsupportedEncodingException e) {
System.out.println("++转码失败++");
}
return strUTF8;
}