将图片转换为Base64字符串公共类抽取

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编码过的字节数组字符串  
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值