java通过文件的url获取文件的base64工具类

package com.exam.utils;

import sun.misc.BASE64Encoder;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.net.HttpURLConnection;
import java.net.URL;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Base64Utils {
   /* public static String getBase64ByImgUrl(String url){
        String suffix = url.substring(url.lastIndexOf(".") + 1);
        try {
            URL urls = new URL(url);
            ByteArrayOutputStream  baos = new ByteArrayOutputStream();
            Image image = Toolkit.getDefaultToolkit().getImage(urls);
            BufferedImage  biOut = toBufferedImage(image);
            ImageIO.write(biOut, suffix, baos);
            String base64Str = encode(baos.toByteArray(),suffix);
            return base64Str;
        } catch (Exception e) {
            return "";
        }
    }*/

    /**
     30      * 图片转字符串
     31      * @param image
     32      * @return
     33      */
        public static String encode(byte[] image,String suffix ){
               BASE64Encoder decoder = new BASE64Encoder();
               String encodeStr = decoder.encode(image);
               encodeStr = "data:image/"+suffix+";base64,"+encodeStr;
               System.out.println(encodeStr);
               return replaceEnter(encodeStr);
       }

    public static String replaceEnter(String str){
       String reg ="[\n-\r]";
       Pattern p = Pattern.compile(reg);
       Matcher m = p.matcher(str);
       return m.replaceAll("");
    }

    /**
     * 通过图片的url获取图片的base64字符串
     * @param imgUrl    图片url
     * @return    返回图片base64的字符串
     */
    public static String image2Base64(String imgUrl) {
        String suffix = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);

        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try{
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return encode(outStream.toByteArray(),suffix);
        }catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            if(is != null)
            {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outStream != null)
            {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpUrl != null)
            {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }


    public static void main(String[] args) {
        try {
            if (1.0>0.9){
                System.out.println("====");
            }
            String ur2 =  image2Base64("https://www.szenkj.cn/mate/root/mate/image/img_202207261102201.png");
            System.out.println(ur2);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

效果图
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个Java工具类,提供了将文件、图片、PDF、URL转换为Base64编码的方法,以及将Base64编码转换为文件的方法: ```java import java.io.*; import java.net.URL; import java.util.Base64; public class PdfUtil { /** * 将文件转换为Base64编码 * @param file 文件对象 * @return Base64编码字符串 */ public static String fileToBase64(File file) { String base64 = null; InputStream in = null; try { in = new FileInputStream(file); byte[] bytes = new byte[in.available()]; in.read(bytes); base64 = Base64.getEncoder().encodeToString(bytes); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return base64; } /** * 将图片转换为Base64编码 * @param imgUrl 图片地址 * @return Base64编码字符串 */ public static String imageToBase64(String imgUrl) { String base64 = null; InputStream in = null; try { URL url = new URL(imgUrl); in = url.openStream(); byte[] bytes = new byte[in.available()]; in.read(bytes); base64 = Base64.getEncoder().encodeToString(bytes); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return base64; } /** * 将PDF文件转换为Base64编码 * @param file PDF文件对象 * @return Base64编码字符串 */ public static String pdfToBase64(File file) { String base64 = null; InputStream in = null; try { in = new FileInputStream(file); byte[] bytes = new byte[in.available()]; in.read(bytes); base64 = Base64.getEncoder().encodeToString(bytes); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return base64; } /** * 将Base64编码保存为文件 * @param base64 Base64编码字符串 * @param filePath 文件保存路径 * @return 文件对象 */ public static File base64ToFile(String base64, String filePath) { File file = null; OutputStream out = null; try { byte[] bytes = Base64.getDecoder().decode(base64); file = new File(filePath); out = new FileOutputStream(file); out.write(bytes); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } return file; } } ``` 使用方法如下: ```java // 将文件转换为Base64编码 File file = new File("example.pdf"); String base64 = PdfUtil.fileToBase64(file); // 将图片转换为Base64编码 String imgUrl = "https://example.com/image.png"; String base64 = PdfUtil.imageToBase64(imgUrl); // 将PDF文件转换为Base64编码 File pdfFile = new File("example.pdf"); String base64 = PdfUtil.pdfToBase64(pdfFile); // 将Base64编码保存为文件 File file = PdfUtil.base64ToFile(base64, "example.pdf"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值