java把图片转为流byte[]数组存到数据库,然后下载图片

文件工具类

package com.ph.rfwg.util;



import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.UUID;


public class FileUtil {
    @Value("${uploadFilePath}")
    private String uploadFilePath;

    private FileUtil() {

    }

    /**
     * File转换为byte[]
     * @param file
     * @return
     */
    public static byte[] getBytesByFile(File file) {
        try {
            //获取输入流
            FileInputStream fis = new FileInputStream(file);

            //新的 byte 数组输出流,缓冲区容量1024byte
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            //缓存
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            //改变为byte[]
            byte[] data = bos.toByteArray();
            //
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws IOException {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            if (!targetFile.mkdirs()) {
                throw new IOException();
            }
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath + "/" + fileName);
            out.write(file);
            out.flush();
        } catch (IOException e) {
            throw new IOException();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        }
        return false;

    }

    public static String renameToUUID(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 文件删除方法
     *
     * @param fileAddress
     * @return
     */
    public static boolean deleteQuietly(String fileAddress) {
        File file = new File(fileAddress);
        if (file == null) {
            return false;
        } else {
            try {
                if (file.isDirectory()) {
//                    cleanDirectory(file);
                }
            } catch (Exception var3) {
                ;
            }

            try {
                return file.delete();
            } catch (Exception var2) {
                return false;
            }
        }
    }

    /**
     * 下载本地文件
     * @param response
     * @param filePath
     * @param encode
     */
    public static void downloadLocal(HttpServletResponse response, String filePath,String encode) {
        response.setContentType("text/html;charset=" + encode);
        try {
            // 读到流中
            InputStream inStream = new FileInputStream(filePath); // 文件的存放路径
            // path是指欲下载的文件的路径
            File file = new File(filePath);
            // 取得文件名
            String fileName = file.getName();
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(encode), "ISO8859-1") + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过文件路径直接修改文件名
     *
     * @param filePath    需要修改的文件的完整路径
     * @param newFileName 需要修改的文件的名称
     * @return
     */
    public static String FixFileName(String filePath, String newFileName) {
        File f = new File(filePath);
        if (!f.exists()) { // 判断原文件是否存在(防止文件名冲突)
            return null;
        }
        newFileName = newFileName.trim();
        if ("".equals(newFileName) || newFileName == null) // 文件名不能为空
            return null;
        String newFilePath = null;
        if (f.isDirectory()) { // 判断是否为文件夹
            newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName;
        } else {
            newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName;
        }
        File nf = new File(newFilePath);
        try {
            f.renameTo(nf); // 修改文件名
        } catch (Exception err) {
            err.printStackTrace();
            return null;
        }
        return newFilePath;
    }

    /*
     *写文件
     */
    public static boolean write(String filePath, String fileName, String fileContent) throws IOException {
        boolean result = false;
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            if (!targetFile.mkdirs()) {
                throw new IOException();
            }
        }

        try {
            FileOutputStream fs = new FileOutputStream(filePath+"/"+fileName);
            //byte[] b = fileContent.getBytes();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fs, "UTF-8"));
          /*

            带bom的utf8

            fs.write( 0xef );

            fs.write( 0xbb);

            fs.write( 0xbf);*/
            writer.write(fileContent);
            writer.flush();
            writer.close();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    //需要注意的是当删除某一目录时,必须保证该目录下没有其他文件才能正确删除,否则将删除失败。
    public static boolean  deleteFolder(File folder) throws Exception {
        boolean flag = false;
        if (!folder.exists()) {
            throw new Exception("文件不存在");
        }
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    //递归直到目录下没有文件
                    deleteFolder(file);
//                    System.err.println("删除目录下所有文件");
                    flag=true;
                } else {
                    //删除
                    file.delete();
//                    System.err.println("删除文件夹里面的文件");
                    flag=true;
                }
            }
        }
        //删除
        folder.delete();
        return flag;
    }

    public static void downloadFile(HttpServletResponse resp, String downloadPath) throws IOException {
        String filePath = null;
        try {

            filePath= URLDecoder.decode(downloadPath,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //String realPath = "D:" + File.separator + "apache-tomcat-8.5.15" + File.separator + "files";
        String realPath=filePath;//项目路径下你存放文件的地方
        File file = new File(realPath);
        if(!file.exists()){
            throw new IOException("文件不存在");
        }
        String name = new String(file.getName().getBytes("GBK"), "ISO-8859-1");
        resp.reset();
        /*
         * 跨域配置
         * */
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        resp.addHeader("Access-Control-Allow-Headers", "Content-Type");

        resp.setContentType("application/octet-stream");
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        resp.setHeader("Content-Disposition", "attachment;filename=" + name);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

我是把本地文件存到数据库

 // 附件流,参数是附件路径
byte[] bytesByFile = FileUtil.getBytesByFile(new File(uploadFilePath + "/" + attachPath));

之后调用sql存进数据库即可
在这里插入图片描述

验证是否存储成功

调用图片下载方法

package com.ph.rfwgzw.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.UUID;

public class ImageUtil {

	/**
	 * @Description: 将base64编码字符串转换为图片
	 * @Author:
	 * @CreateTime:
	 * @param file base64编码字符串
	 * @param path 图片路径-具体到文件
	 * @return
	 */
	public static String generateImage(String file, String path) {
		// 解密
		try {
			// 图片分类路径+图片名+图片后缀
			String imgClassPath = path.concat(UUID.randomUUID().toString()).concat(".jpg");
			// 解密
//			Base64.Decoder decoder = Base64.getDecoder();
			Base64.Decoder decoder = Base64.getMimeDecoder();

			// 去掉base64前缀 data:image/jpeg;base64,
			file = file.substring(file.indexOf(",", 1) + 1, file.length());
			byte[] b = decoder.decode(file);
			// 处理数据
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			// 保存图片
			OutputStream out = new FileOutputStream("E://".concat(imgClassPath));
			out.write(b);
			out.flush();
			out.close();
			// 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
			return imgClassPath;
		} catch (IOException e) {
			return null;
		}
	}
}

// 最后在控制器或者main方法里面调用该方法测试即可
ImageUtil.generateImage(str,"ceshi");

如果是把别人的base64位编码存到数据库,也要转换
参考链接:https://blog.csdn.net/wang8978/article/details/52279661

String content = attachMap.get("content").toString();
BASE64Decoder dec=new BASE64Decoder();
byte[]after=null;
try {
    after =dec.decodeBuffer(content);//使用BASE64解码
} catch (Exception e) {
    e.getMessage();
}
要生成二维码并将其保存到数据库,您可以使用以下步骤: 1. 导入相关的Java库:您可以使用ZXing库来生成二维码。请确保已将其添加到您的Java项目。 2. 生成二维码:使用ZXing库的QRCodeWriter类,您可以创建一个QRCode对象,该对象可以转换为图片格式并保存到本地。 3. 将二维码图片转换为字节数组:使用ImageIO类将二维码图片转换为字节数组。 4. 将字节数组存到数据库:使用JDBC连接到您的数据库,并使用PreparedStatement类将字节数组存到数据库。 以下是一些示例代码来演示这些步骤: ```java import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Base64; import javax.imageio.ImageIO; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class QRCodeGenerator { public static void main(String[] args) throws SQLException { String data = "Hello, world!"; // 数据内容 int size = 300; // 生成二维码图片大小 String format = "png"; // 二维码图片格式 byte[] imageBytes = null; // 生成二维码 QRCodeWriter writer = new QRCodeWriter(); BitMatrix matrix; try { matrix = writer.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, size, size); BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, format, baos); imageBytes = baos.toByteArray(); } catch (WriterException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // 将字节数组存到数据库 Connection conn = null; // 假设您已连接到数据库 PreparedStatement ps = conn.prepareStatement("INSERT INTO qr_codes (data) VALUES (?)"); ps.setBytes(1, imageBytes); ps.executeUpdate(); } } ``` 在这个示例,我们生成一个包含字符串“Hello, world!”的二维码,将其转换为PNG格式的图片,将图片字节数组存到名为“qr_codes”的数据库。请注意,此示例仅用于演示目的,您需要根据您的具体需求进行适当的修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值