zoukankan      html  css  js  c++  java
  • java上传不同类型图片,保存数据库(Base64位图转网络图片)

    直接上代码好不好

    方法名:

    GenerateImage
    传参:
    base64Img:上传的base64码
    realPath:生成的图片路径 
    imgTypes :图片类型

     
    String imgBase64 = request.getParameter("userImgbase64");
    // 获取当前服务器路径
     String realPath = request.getServletContext().getRealPath("")+"\img"; 
    System.out.println(
    realPath ); //  http://192.168.191.1:8080/MyWeb/img


    String[] imgType = imgBase64.split(",");

    // 获取图片类型(如果没有类型,貌似会报错)
    String imgTypes = imgType[0].toString().substring(11, imgType[0].toString().length()-7);


    String userImgbase64 = GenerateImage(imgBase64,realPath,imgTypes);
    System.out.println(realPath );   //  http://192.168.191.1:8080/MyWeb/img/1532493648717.png

    //
    对字节数组字符串进行Base64解码并生成图片 public static String GenerateImage(String base64Img,String realPath,String imgTypes ){ String ret_fileName = null; // 临时文件路径 File file_normer = new File(realPath+"/"); if (!file_normer.exists()) { file_normer.mkdirs(); } if (base64Img == null) // 图像数据为空 return "图像数据为空"; base64Img = base64Img.replaceAll("data:image/"+imgTypes+";base64,", ""); BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解码 byte[] b = decoder.decodeBuffer(base64Img); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 调整异常数据 b[i] += 256; } } // 生成jpeg图片 ret_fileName = System.currentTimeMillis()+"."+imgTypes+""; File file = new File(realPath + "/" + ret_fileName ); OutputStream out = new FileOutputStream(file); out.write(b); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return ret_fileName ; }
  • 相关阅读:
    常见的排序算法--java版
    使用final关键字修饰一个变量时,是引用不能变,还是引用的对象不能变?
    在JAVA中如何跳出当前的多重嵌套循环
    说说&和&&的区别
    家族/亲戚(relation)
    面积(area)
    珍珠(bead)
    N皇后问题
    纪念品分组 2007年NOIP全国联赛普及组
    二叉树的序遍历
  • 原文地址:https://www.cnblogs.com/zhuyupingit/p/9454354.html
Copyright © 2011-2022 走看看