zoukankan      html  css  js  c++  java
  • 图片转二进制——各种方法汇总(转载)

    使用Base64转换图片

         利用Base64实现二进制和图片之间的转换,具体代码如下:

    [java] view plain copy
     
    1. import java.awt.image.BufferedImage;  
    2. import java.io.ByteArrayInputStream;  
    3. import java.io.ByteArrayOutputStream;  
    4. import java.io.File;  
    5. import java.io.IOException;  
    6.   
    7. import javax.imageio.ImageIO;  
    8.   
    9. import org.apache.tomcat.util.codec.binary.Base64;  
    10.   
    11. public class ImageBinary {  
    12.   
    13.     public static void main(String[] args) {  
    14.         String fileName = "D://code//test.jpg";  
    15.         System.out.println(getImageBinary(fileName));  
    16.         saveImage(getImageBinary(fileName));  
    17.     }  
    18.   
    19.     /* 
    20.      * 图片转换为二进制 
    21.      *  
    22.      * @param fileName 
    23.      *            本地图片路径 
    24.      * @return 
    25.      *       图片二进制流 
    26.      * */  
    27.     public static String getImageBinary(String fileName) {  
    28.         File f = new File(fileName);  
    29.         BufferedImage bi;  
    30.         try {  
    31.             bi = ImageIO.read(f);  
    32.             ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    33.             ImageIO.write(bi, "jpg", baos);  
    34.             byte[] bytes = baos.toByteArray();  
    35.             return Base64.encodeBase64String(bytes);  
    36.             //return encoder.encodeBuffer(bytes).trim();  
    37.         } catch (IOException e) {  
    38.             e.printStackTrace();  
    39.         }  
    40.         return null;  
    41.     }  
    42.   
    43.     /** 
    44.      * 将二进制转换为图片 
    45.      *  
    46.      * @param base64String 
    47.      *            图片二进制流 
    48.      *        
    49.      */  
    50.     public static void saveImage(String base64String) {  
    51.         try {  
    52.             byte[] bytes1 = Base64.decodeBase64(base64String);  
    53.             ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);  
    54.             BufferedImage bi1 = ImageIO.read(bais);  
    55.             File w2 = new File("D://code//22.jpg");// 可以是jpg,png,gif格式  
    56.             ImageIO.write(bi1, "jpg", w2);// 不管输出什么格式图片,此处不需改动  
    57.         } catch (IOException e) {  
    58.             e.printStackTrace();  
    59.         }  
    60.     }  
    61. }  

    url获取图片字节流

        若通过url访问图片并转换为二进制流,就不能按照上述方法。通过url获取图片涉及url、网络状态等各种情况。在代码中涉及两种不同的方法:一个是通过url的形式,另一个是直接访问本地资源(即图片路径)。详见以下代码:

    [java] view plain copy
     
    1. import java.io.ByteArrayOutputStream;  
    2. import java.io.File;  
    3. import java.io.FileInputStream;  
    4. import java.io.IOException;  
    5. import java.io.InputStream;  
    6. import java.net.HttpURLConnection;  
    7. import java.net.URL;  
    8.   
    9. public class ImageUtil {  
    10.   
    11.     /** 
    12.      * 根据地址获得数据的字节流 
    13.      * 
    14.      * @param strUrl 
    15.      *            网络连接地址 
    16.      * @return 
    17.      */  
    18.     public static byte[] getImageFromNetByUrl(String strUrl) {  
    19.         try {  
    20.             URL url = new URL(strUrl);  
    21.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
    22.             conn.setRequestMethod("GET");  
    23.             conn.setConnectTimeout(5 * 1000);  
    24.             InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据  
    25.             byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据  
    26.             return btImg;  
    27.         } catch (Exception e) {  
    28.             e.printStackTrace();  
    29.         }  
    30.         return null;  
    31.     }  
    32.   
    33.     /** 
    34.      * 根据地址获得数据的字节流 
    35.      * 
    36.      * @param strUrl 
    37.      *            本地连接地址 
    38.      * @return 
    39.      */  
    40.     public byte[] getImageFromLocalByUrl(String strUrl) {  
    41.         try {  
    42.             File imageFile = new File(strUrl);  
    43.             InputStream inStream = new FileInputStream(imageFile);  
    44.             byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据  
    45.             return btImg;  
    46.         } catch (Exception e) {  
    47.             e.printStackTrace();  
    48.         }  
    49.         return null;  
    50.     }  
    51.   
    52.     /** 
    53.      * 从输入流中获取数据 
    54.      * 
    55.      * @param inStream 
    56.      *            输入流 
    57.      * @return 
    58.      * @throws IOException 
    59.      * @throws Exception 
    60.      */  
    61.     private static byte[] readInputStream(InputStream inStream) throws IOException {  
    62.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
    63.         byte[] buffer = new byte[10240];  
    64.         int len = 0;  
    65.         while ((len = inStream.read(buffer)) != -1) {  
    66.             outStream.write(buffer, 0, len);  
    67.         }  
    68.         inStream.close();  
    69.         return outStream.toByteArray();  
    70.   
    71.     }  
    72.       
    73.     public static void main(String[] args) {  
    74.         String url = "https://images0.cnblogs.com/blog/536814/201412/051633343733092.png";  
    75.         byte[] b = getImageFromNetByUrl(url);  
    76.         System.out.println(b);  
    77.     }  
    78. }  

    url获取图片字节流

       本节介绍的方法可以说是前两种方法的结合体,但是在两者的基础上有所优化,如对url的状态做判断,此方法仅供参考,可根据具体需求做相应调整。

    [java] view plain copy
     
    1. import java.awt.image.BufferedImage;  
    2. import java.io.BufferedInputStream;  
    3. import java.io.ByteArrayOutputStream;  
    4. import java.net.HttpURLConnection;  
    5. import java.net.URL;  
    6. import java.net.URLConnection;  
    7.   
    8. import javax.imageio.ImageIO;  
    9.   
    10. import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;  
    11.   
    12. public class ImageUtils {  
    13.   
    14.     /* 
    15.      * 获取原图片二进制流 
    16.      *  
    17.      * @param imageUrl 
    18.      *             原图片地址 
    19.      * */  
    20.     public static String getImageBinary(String imageUrl) {  
    21.         String data = null;  
    22.         try {  
    23.             int HttpResult = 0; // 服务器返回的状态  
    24.             URL url = new URL(imageUrl); // 创建URL  
    25.             URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码  
    26.             urlconn.connect();  
    27.             HttpURLConnection httpconn = (HttpURLConnection) urlconn;  
    28.             HttpResult = httpconn.getResponseCode();  
    29.             if (HttpResult != HttpURLConnection.HTTP_OK) // 不等于HTTP_OK则连接不成功  
    30.                 System.out.print("failed");  
    31.             else {  
    32.                 BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());  
    33.                 BufferedImage bm = ImageIO.read(bis);  
    34.                 ByteArrayOutputStream bos = new ByteArrayOutputStream();  
    35.                 String type = imageUrl.substring(imageUrl.length() - 3);  
    36.                 ImageIO.write(bm, type, bos);  
    37.                 bos.flush();  
    38.                 data = Base64.encode(bos.toByteArray());  
    39.                 bos.close();  
    40.             }  
    41.         } catch (Exception e) {  
    42.             e.printStackTrace();  
    43.         }  
    44.         return data;  
    45.   
    46.     }  
    47.   
    48.     public static void main(String[] args) {  
    49.         String url = "https://images0.cnblogs.com/blog/536814/201412/051633343733092.png";  
    50.         String result = getImageBinary(url);  
    51.         System.out.println(result);  
    52.     }  
    53. }  

    url获取图片字节流

       本方法实现了主要实现了以下几个功能:

       1、通过url将图片转换为字节流(十六进制的形式),并实现字节流与图片之间的相互转换;

       2、将本地图片转换为字节流(十六进制的形式),并实现字节流与图片之间的相互转换;

    [java] view plain copy
     
    1. import java.awt.image.BufferedImage;  
    2. import java.io.BufferedInputStream;  
    3. import java.io.ByteArrayOutputStream;  
    4. import java.io.File;  
    5. import java.io.FileInputStream;  
    6. import java.io.IOException;  
    7. import java.io.InputStream;  
    8. import java.io.RandomAccessFile;  
    9. import java.net.HttpURLConnection;  
    10. import java.net.URL;  
    11. import java.net.URLConnection;  
    12.   
    13. import javax.imageio.ImageIO;  
    14.   
    15. public class Utils {  
    16.     /** 
    17.      * 图片转换成二进制字符串 
    18.      *  
    19.      * @param imageUrl 
    20.      *            图片url 
    21.      * @return String 二进制流 
    22.      */  
    23.     public static String getImgeHexStringByUrl(String imageUrl) {  
    24.         String res = null;  
    25.         try {  
    26.             int HttpResult = 0; // 服务器返回的状态  
    27.             URL url = new URL(imageUrl); // 创建URL  
    28.             URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码  
    29.             urlconn.connect();  
    30.             HttpURLConnection httpconn = (HttpURLConnection) urlconn;  
    31.             HttpResult = httpconn.getResponseCode();  
    32.             if (HttpResult != HttpURLConnection.HTTP_OK) // 不等于HTTP_OK则连接不成功  
    33.                 System.out.print("failed");  
    34.             else {  
    35.                 BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());  
    36.                 BufferedImage bm = ImageIO.read(bis);  
    37.                 ByteArrayOutputStream bos = new ByteArrayOutputStream();  
    38.                 String type = imageUrl.substring(imageUrl.length() - 3);  
    39.                 ImageIO.write(bm, type, bos);  
    40.                 bos.flush();  
    41.                 byte[] data = bos.toByteArray();  
    42.                 res = byte2hex(data);  
    43.                 bos.close();  
    44.             }  
    45.         } catch (Exception e) {  
    46.             e.printStackTrace();  
    47.         }  
    48.         return res;  
    49.     }  
    50.   
    51.     /** 
    52.      * 本地图片转换成二进制字符串 
    53.      *  
    54.      * @param imageUrl 
    55.      *            图片url 
    56.      * @return String 二进制流 
    57.      */  
    58.     public static String getImgeHexStringByLocalUrl(String imageUrl) {  
    59.         String res = null;  
    60.   
    61.         try {  
    62.             File imageFile = new File(imageUrl);  
    63.             InputStream inStream = new FileInputStream(imageFile);  
    64.             BufferedInputStream bis = new BufferedInputStream(inStream);  
    65.             BufferedImage bm = ImageIO.read(bis);  
    66.             ByteArrayOutputStream bos = new ByteArrayOutputStream();  
    67.             String type = imageUrl.substring(imageUrl.length() - 3);  
    68.             ImageIO.write(bm, type, bos);  
    69.             bos.flush();  
    70.             byte[] data = bos.toByteArray();  
    71.             res = byte2hex(data);  
    72.             bos.close();  
    73.         } catch (Exception e) {  
    74.             e.printStackTrace();  
    75.         }  
    76.         return res;  
    77.     }  
    78.   
    79.     /** 
    80.      * @title 根据二进制字符串生成图片 
    81.      * @param data 
    82.      *            生成图片的二进制字符串 
    83.      * @param fileName 
    84.      *            图片名称(完整路径) 
    85.      * @param type 
    86.      *            图片类型 
    87.      * @return 
    88.      */  
    89.     public static void saveImage(String data, String fileName, String type) {  
    90.   
    91.         BufferedImage image = new BufferedImage(300, 300, BufferedImage.TYPE_BYTE_BINARY);  
    92.         ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();  
    93.         try {  
    94.             ImageIO.write(image, type, byteOutputStream);  
    95.             // byte[] date = byteOutputStream.toByteArray();  
    96.             byte[] bytes = hex2byte(data);  
    97.             RandomAccessFile file = new RandomAccessFile(fileName, "rw");  
    98.             file.write(bytes);  
    99.             file.close();  
    100.         } catch (IOException e) {  
    101.             e.printStackTrace();  
    102.         }  
    103.     }  
    104.   
    105.     /** 
    106.      * 反格式化byte 
    107.      *  
    108.      * @param s 
    109.      * @return 
    110.      */  
    111.     public static byte[] hex2byte(String s) {  
    112.         byte[] src = s.toLowerCase().getBytes();  
    113.         byte[] ret = new byte[src.length / 2];  
    114.         for (int i = 0; i < src.length; i += 2) {  
    115.             byte hi = src[i];  
    116.             byte low = src[i + 1];  
    117.             hi = (byte) ((hi >= 'a' && hi <= 'f') ? 0x0a + (hi - 'a') : hi - '0');  
    118.             low = (byte) ((low >= 'a' && low <= 'f') ? 0x0a + (low - 'a') : low - '0');  
    119.             ret[i / 2] = (byte) (hi << 4 | low);  
    120.         }  
    121.         return ret;  
    122.     }  
    123.   
    124.     /** 
    125.      * 格式化byte 
    126.      *  
    127.      * @param b 
    128.      * @return 
    129.      */  
    130.     public static String byte2hex(byte[] b) {  
    131.         char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  
    132.         char[] out = new char[b.length * 2];  
    133.         for (int i = 0; i < b.length; i++) {  
    134.             byte c = b[i];  
    135.             out[i * 2] = Digit[(c >>> 4) & 0X0F];  
    136.             out[i * 2 + 1] = Digit[c & 0X0F];  
    137.         }  
    138.   
    139.         return new String(out);  
    140.     }  
    141.   
    142.     public static void main(String[] args) {  
    143.         String fileName = "D://code//cc.png";  
    144.         String url = "https://images0.cnblogs.com/blog/536814/201412/051633343733092.png";  
    145.         String outImage = "D://code//11.png";  
    146.         /* 
    147.          * url形式 
    148.          * */  
    149.         String result = getImgeHexStringByUrl(url);  
    150.         System.out.println(result);  
    151.         saveImage(result,fileName,"png");  
    152.         /* 
    153.          * 本地图片形式 
    154.          * */  
    155.         String result1 = getImgeHexStringByLocalUrl(fileName);  
    156.         System.out.println(result1);  
    157.         saveImage(result1,outImage,"png");  
    158.     }  
    159.   
    160. }  

    通过url下载图片

       在给定url的情况下,可将url所访问的图片下载至本地。具体代码如下:

    [java] view plain copy
     
    1. import java.io.BufferedInputStream;  
    2. import java.io.FileOutputStream;  
    3. import java.io.IOException;  
    4. import java.net.HttpURLConnection;  
    5. import java.net.URL;  
    6.   
    7. public class downimageUtil {  
    8.   
    9.     private static final String filePath = "C://Users//lizhihui//Desktop//";  
    10.   
    11.     /* 
    12.      * 根据url下载图片 
    13.      *  
    14.      * @param  destUrl 
    15.      *             url连接 
    16.      * @return  
    17.      *       图片保存路径 
    18.      * */  
    19.     public String saveToFile(String destUrl) {  
    20.         String fileName = "";  
    21.         FileOutputStream fos = null;  
    22.         BufferedInputStream bis = null;  
    23.         HttpURLConnection httpUrl = null;  
    24.         URL url = null;  
    25.         int BUFFER_SIZE = 1024;  
    26.         byte[] buf = new byte[BUFFER_SIZE];  
    27.         int size = 0;  
    28.         try {  
    29.             url = new URL(destUrl);  
    30.             httpUrl = (HttpURLConnection) url.openConnection();  
    31.             httpUrl.connect();  
    32.             bis = new BufferedInputStream(httpUrl.getInputStream());  
    33.             for (String string : destUrl.split("/")) {  
    34.                 if (string.contains("png") || string.contains("png") || string.contains("gif")) {  
    35.                     fileName = string;  
    36.                 }  
    37.             }  
    38.             fos = new FileOutputStream(filePath + fileName);  
    39.             while ((size = bis.read(buf)) != -1) {  
    40.                 fos.write(buf, 0, size);  
    41.             }  
    42.             fos.flush();  
    43.         } catch (IOException e) {  
    44.         } catch (ClassCastException e) {  
    45.         } finally {  
    46.             try {  
    47.                 fos.close();  
    48.                 bis.close();  
    49.                 httpUrl.disconnect();  
    50.             } catch (IOException e) {  
    51.             } catch (NullPointerException e) {  
    52.             }  
    53.         }  
    54.         return filePath + fileName;  
    55.     }  
    56.       
    57.     public static void main(String[] args) {  
    58.         downimageUtil dw = new downimageUtil();  
    59.         String url = "https://images0.cnblogs.com/blog/536814/201412/051633343733092.png";  
    60.         System.out.println(dw.saveToFile(url));  
    61.     }  
    62. }  


       到此,对于图片的处理结束,这是在写图片压缩服务器时所用到的部分技术,当然在此基本上有所改进,在此不再一一列举,对于图片的压缩方法后续也会整理出来,欢迎查看!虽然写出来了,但还没进行压力测试,优化等一系列后续工作。就先这样吧......

    转载自:https://blog.csdn.net/hh12211221/article/details/74639049

  • 相关阅读:
    可遇不可求的Question之DateTime.Ticks的单位篇(囧rz)
    可遇不可求的Question之SQLLite创建持久视图篇
    可遇不可求的Question之FusionCharts图表显示异常的解决办法
    可遇不可求的Question之安装的.NET Framework版本以及Service Pack
    可遇不可求的Question之不支持一个STA 线程上针对多个句柄的WaitAll
    可遇不可求的Question之Regex.Split解析乱码字符串异常篇
    Protocol Buffers proto语言语法说明
    [转]网页轻松绘制流程图:Diagramly
    笔记:代码整洁之道
    类之间的关系
  • 原文地址:https://www.cnblogs.com/yinyl/p/8890810.html
Copyright © 2011-2022 走看看