Keep Running

导航

解决android客户端上传图片到服务端时,图片损坏的问题

  1. 问题:客户端是android,通过json传输图片到服务端,服务端解析出来,生成图片时损坏。
  • 在客户端将图片转为string格式,这里要注意的是通过Base64.encode进行编码,再通过jackson序列化
     1 /**
     2      * 利用BASE64Encoder对图片进行base64转码将图片转为string
     3      * 
     4      * @param imgFile 文件路径
     5      * @return 返回编码后的string
     6      */
     7     public static String f_imageToString(String imgFile)
     8     {
     9         // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
    10         InputStream in = null;
    11         byte[] data = null;
    12         // 读取图片字节数组
    13         try
    14         {
    15             in = new FileInputStream(imgFile);
    16             data = new byte[in.available()];
    17             in.read(data);
    18             in.close();
    19         }
    20         catch (IOException e)
    21         {
    22             e.printStackTrace();
    23         }
    24         // 返回Base64编码过的字节数组字符串
    25         String str = new String(Base64.encode(data));
    26         return str;
    27     }

     

  • 在服务端通过jackson取到base64编码后传过来的string数据,再进行base64解码,生成图片
     1 /**
     2      * 通过BASE64Decoder解码,并生成图片
     3      * 
     4      * @param imgStr 解码后的string
     5      * @return
     6      */
     7     public static boolean f_stringToImage(String imgStr, String imgFilePath)
     8     {
     9         // 对字节数组字符串进行Base64解码并生成图片
    10         if (imgStr == null)
    11             return false;
    12         try
    13         {
    14             // Base64解码
    15             byte[] b = Base64.decode(imgStr);
    16             for (int i = 0; i < b.length; ++i)
    17             {
    18                 if (b[i] < 0)
    19                 {
    20                     // 调整异常数据
    21                     b[i] += 256;
    22                 }
    23             }
    24             // 生成jpeg图片
    25             OutputStream out = new FileOutputStream(imgFilePath);
    26             out.write(b);
    27             out.flush();
    28             out.close();
    29             return true;
    30         }
    31         catch (Exception e)
    32         {
    33             return false;
    34         }
    35     }


     

posted on 2012-05-30 18:24  Keep Running  阅读(4834)  评论(2编辑  收藏  举报