public class ImageToBase64 {

     //图片转化成base64字符串
public static String GetImageStr(String path,int width,int height) throws IOException
{//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
File srcFile = new File(path);//文件上服务器上面的地址
if (!srcFile.exists())
return "";
Image srcImg = ImageIO.read(srcFile);
// 生成指定大小图片
BufferedImage buffImg = null;
int oldWidth = srcImg.getWidth(null);
int oldHeight = srcImg.getHeight(null);
// 计算原图等比缩放长宽
if (oldWidth * height > width * oldHeight) {
oldHeight = width * oldHeight / oldWidth;
oldWidth = width;
} else {
oldWidth = height * oldWidth / oldHeight;
oldHeight = height;
}
// 生成新图
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 填白
buffImg.getGraphics().fillRect(0, 0, width, height);
// 填入原图
buffImg.getGraphics().drawImage(srcImg.getScaledInstance(oldWidth, oldHeight, Image.SCALE_SMOOTH),
(width - oldWidth) / 2, (height - oldHeight) / 2, null); ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
ImageIO.write(buffImg, "jpg", imOut); InputStream in = new ByteArrayInputStream(bs.toByteArray());
byte[] data = null;
//读取图片字节数组
try
{
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
return "";
}
// String fileName=srcFile.getName();
//String prefix="data:image/jpg"+fileName.substring(fileName.lastIndexOf(".")+1)+";base64,";
String prefix="data:image/jpg;base64,";
return prefix+Base64.encodeBase64String(data);//返回Base64编码过的字节数组字符串
}
}

最新文章

  1. partial class的使用范围
  2. activeMq 消费者整合spring
  3. 关于delegate(代理)总结
  4. 探讨Nodejs中的作用域问题。
  5. 试用vSphere 6(三):安装vCenter 6(独立数据库)之:vCenter安装与配置
  6. Java并发编程(一) 两种实现多线程的方法(Thread,Runnable)
  7. Linux基础 30分钟GDB调试快速突破
  8. 实用Linux命令,不求最全但求实用-------磁盘使用情况du,df
  9. struts文件上传和下载
  10. Google Chrome调试js代码
  11. chrome开发工具指南(二)
  12. 智能合约语言 Solidity 教程系列5 - 数组介绍
  13. Python excel 奇怪的通信规则
  14. Linux 桌面玩家指南:03. 针对 Gnome 3 的 Linux 桌面进行美化
  15. 第四次上机,ASP组件的使用
  16. 在Linux上要安装SSH协议
  17. MySql 注意点
  18. navigateTo、redirectTo、switchTap与reLaunch的区别
  19. 修改Ubuntu的aptget源为阿里源的方法
  20. HTTP 错误 404.17 - Not Found和 HTTP 错误 404.2 - Not Found 解决办法

热门文章

  1. C# 网络编程小计 20150202
  2. MYSQL5.5源码安装 linux下
  3. Codeforces 707C Pythagorean Triples(构造三条边都为整数的直角三角形)
  4. MySQL关键字大全
  5. python中global变量释疑
  6. 将xml文件转为c#对像
  7. 编写.gitignore 文件
  8. POJ3468 A Simple Problem with Interger [树状数组,差分]
  9. PHP超全局变量数组
  10. 基于wsimport生成代码的客户端