把前端经过Base64算法转换的图片字符串处理为图片文件并保存的关键代码


public class CropsImageVo {

    //作物生长全局图片
    private String imageBase64;

    public String getImageBase64() {
        return imageBase64;
    }

    public void setImageBase64(String imageBase64) {
        this.imageBase64 = imageBase64;
    }

    @Override
    public String toString() {
        return "CropsImageVo{" +
                "imageBase64='" + imageBase64 + '/'' +
                '}';
    }
}
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Base64Util {
    public static File base64ConvertFile(String s) {
        String filePath = "D://myofficework//resouce//";
        String fileName = System.currentTimeMillis()+".jpg";
        BASE64Decoder decoder = new BASE64Decoder();
        File file = null;
        try {
            byte[] bytes = decoder.decodeBuffer(s);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            String imageFilePath = filePath+fileName;
            //System.out.println("************" + imageFilePath22);
            //String imageFilePath = filePath+fileName.replace("////","/");
            //System.out.println("************" + imageFilePath);
            OutputStream out = new FileOutputStream(imageFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            System.out.println("图片上传成功");
            file = new File(imageFilePath);
        }catch (IOException e){
            e.printStackTrace();
        }
        return file;
    }
}
    @PostMapping("imageUpload")
    public AjaxResult imageUpload(@RequestBody CropsImageVo cropsImageVo) throws FileNotFoundException {
        //替换掉部分图片字符串信息
        String imageBase64 = cropsImageVo.getImageBase64().replace("data:image/jpeg;base64,", "");
        //System.out.println(imageBase64);
        //保存图片并返回图片文件对象
        File file = Base64Util.base64ConvertFile(imageBase64);
        StorePath storePath = this.fastFileStorageClient.uploadImageAndCrtThumbImage(new FileInputStream(file),file.length(),"jpg",null);
        return AjaxResult.success(address+storePath.getFullPath());
    }

 

原创文章,作者:Carrie001128,如若转载,请注明出处:https://blog.ytso.com/244310.html

(0)
上一篇 2022年4月17日
下一篇 2022年4月17日

相关推荐

发表回复

登录后才能评论