Java two ways to get the base64 bit string of the picture through the picture url address Java two ways to get the base64 bit string of the picture through the picture url address

In the work, I encountered the need to get the base64 of the picture through the URL of the picture. At the beginning, I used the online method through Toolkit. Although the implementation code is relatively short, I occasionally encounter the situation that the picture is converted to base64 bit incorrectly.

After that, I went online and searched for a way to convert the binary stream of the image into base64. Both methods are effective for pro test. Occasionally appear through Toolkit. After switching to base64, the problem of incomplete display is displayed. So it is recommended to convert by downloading binary stream conversion.

Attach the code below:

Copy code
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;


import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.net.HttpURLConnection;
import java.net.URL;


public class ImageUtils {

    
    
    public static String getBase64ByImgUrl(String url){
        String suffix = url.substring(url.lastIndexOf(".") + 1);
        try {
            URL urls = new URL(url);
            ByteArrayOutputStream  baos = new ByteArrayOutputStream();
            Image image = Toolkit.getDefaultToolkit().getImage(urls);
            BufferedImage  biOut = toBufferedImage(image);
            ImageIO.write(biOut, suffix, baos);
            String base64Str = Base64Util.encode(baos.toByteArray());
            return base64Str;
        } catch (Exception e) {
            return "";
        }
        
    }
    
    public static BufferedImage toBufferedImage(Image image) {  
        if (image instanceof BufferedImage) {  
            return (BufferedImage) image;  
        }  
        // This code ensures that all the pixels in the image are loaded  
        image = new ImageIcon(image).getImage();  
        BufferedImage bimage = null;  
        GraphicsEnvironment ge = GraphicsEnvironment  
                .getLocalGraphicsEnvironment();  
        try {  
            int transparency = Transparency.OPAQUE;  
            GraphicsDevice gs = ge.getDefaultScreenDevice();  
            GraphicsConfiguration gc = gs.getDefaultConfiguration();  
            bimage = gc.createCompatibleImage(image.getWidth(null),  
                    image.getHeight(null), transparency);  
        } catch (HeadlessException e) {  
            // The system does not have a screen  
        }  
        if (bimage == null) {   
            // Create a buffered image using the default color model   
            int type = BufferedImage.TYPE_INT_RGB;   
            bimage = new BufferedImage (image.getWidth (null),   
                    image.getHeight (null), type);   
        }   
        / / Copy image to buffered image   
        Graphics g = bimage.createGraphics ();   
        // Paint the image onto the buffered image   
        g.drawImage (image, 0, 0, null);   
        g.dispose ();   
        return bimage;   
    }   
    / ** 
     * Get the base64 string of the picture by the URL of the picture 
     * @param imgUrl Picture url 
     * @return Returns the string of the base64 of the picture
     * / 
     */
    public static String image2Base64(String imgUrl) {  

        URL url = null;   

        InputStream is = null;    

        ByteArrayOutputStream outStream = null;   

        HttpURLConnection httpUrl = null;   

        try {   

            url = new URL (imgUrl);   

            httpUrl = (HttpURLConnection) url.openConnection ();   

            httpUrl.connect ();   

            httpUrl.getInputStream ();   

            is = httpUrl.getInputStream ();             

              

            outStream = new ByteArrayOutputStream (); 

            // Create a Buffer string   

            byte [] buffer = new byte [1024];   

            // The length of each read string, if it is-   1, means all reads are completed   

            int len ​​= 0;   

            // Use an input stream to read data from the buffer  

            while ((len = is.read (buffer))! = -1) {   

                // Use the output stream to write data to the buffer, the middle parameter represents where to start reading, len represents the length of the   

                readoutStream.write (buffer , 0, len);   

            }   

            // Base64 encoding 

            return to byte array   Base64Util.encode (outStream.toByteArray ());   

        } catch (Exception e) {   

            e.printStackTrace ();   

        }   

        finally {   

            if (is! = Null)   

            {   

                try {   

                    is.close ();   

                } catch (IOException e) {   

                    e.printStackTrace ();   

                }   

            }  

            if(outStream != null)  

            {  

                try {  

                    outStream.close();  

                } catch (IOException e) {  

                    e.printStackTrace();  

                }  

            }  

            if(httpUrl != null)  

            {  

                httpUrl.disconnect();  

            }  

        }  

        return imgUrl;  

    }  
}    
Copy code

among them

The getBase64ByImgUrl method is obtained through Toolkit. As for why there is no comment, because I don't understand the principle, I copied it.
The image2Base64 method is by downloading a binary stream, which is of course copied. It is written to summarize. Next time you encounter the same problem, you do n’t have to check it everywhere. 
Attach the Base64Util code:
Copy code
 1 import java.io.ByteArrayOutputStream;
 2 import java.io.File;
 3 import java.io.IOException;
 4 import java.util.regex.Matcher;
 5 import java.util.regex.Pattern;
 6 
 7 import javax.imageio.stream.FileImageInputStream;
 8 
 9 import sun.misc.BASE64Decoder;
10 import sun.misc.BASE64Encoder;
11 
12 public class Base64Util{
13     /**
14      * 字符串转图片
15      * @param base64Str
16      * @return
17      */
18     public static byte[] decode(String base64Str){
19         byte[] b = null;
20         BASE64Decoder decoder = new BASE64Decoder();
21         try {
22             b = decoder.decodeBuffer(replaceEnter(base64Str));
23         } catch (IOException e) {
24             e.printStackTrace();
25         }
26         return b;
27     }
28     
29     /**
30      * 图片转字符串
31      * @param image
32      * @return
33      */
34     public static String encode(byte[] image){
35         BASE64Encoder decoder = new BASE64Encoder();
36         return replaceEnter(decoder.encode(image));
37     }
38     
39     public static String encode(String uri){
40         BASE64Encoder encoder = new BASE64Encoder();
41         return replaceEnter(encoder.encode(uri.getBytes()));
42     }
43     
44     /**
45      * 
46      * @path    图片路径
47      * @return
48      */
49     
50     public static byte[] imageTobyte(String path){
51         byte[] data = null;
52         FileImageInputStream input = null;
53         try {
54             input = new FileImageInputStream(new File(path));
55             ByteArrayOutputStream output = new ByteArrayOutputStream();
56             byte[] buf = new byte[1024];
57             int numBytesRead = 0;
58             while((numBytesRead = input.read(buf)) != -1){
59                 output.write(buf, 0, numBytesRead);
60             }
61             data = output.toByteArray();
62             output.close();
63             input.close();
64             
65         } catch (Exception e) {
66             e.printStackTrace();
67         }
68         
69         return data;
70     }
71     
72     
73     
74     public static String replaceEnter(String str){
75         String reg ="[\n-\r]";
76         Pattern p = Pattern.compile(reg);
77         Matcher m = p.matcher(str);
78         return m.replaceAll("");
79     }
80     
81     
82 }
Copy code

In the work, I encountered the need to get the base64 of the picture through the URL of the picture. At the beginning, I used the online method through Toolkit. Although the implementation code is relatively short, I occasionally encounter the situation that the picture is converted to base64 bit incorrectly.

After that, I went online and searched for a way to convert the binary stream of the image into base64. Both methods are effective for pro test. Occasionally appear through Toolkit. After switching to base64, the problem of incomplete display is displayed. So it is recommended to convert by downloading binary stream conversion.

Attach the code below:

Copy code
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;


import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.net.HttpURLConnection;
import java.net.URL;


public class ImageUtils {

    
    
    public static String getBase64ByImgUrl(String url){
        String suffix = url.substring(url.lastIndexOf(".") + 1);
        try {
            URL urls = new URL(url);
            ByteArrayOutputStream  baos = new ByteArrayOutputStream();
            Image image = Toolkit.getDefaultToolkit().getImage(urls);
            BufferedImage  biOut = toBufferedImage(image);
            ImageIO.write(biOut, suffix, baos);
            String base64Str = Base64Util.encode(baos.toByteArray());
            return base64Str;
        } catch (Exception e) {
            return "";
        }
        
    }
    
    public static BufferedImage toBufferedImage(Image image) {  
        if (image instanceof BufferedImage) {  
            return (BufferedImage) image;  
        }  
        // This code ensures that all the pixels in the image are loaded  
        image = new ImageIcon(image).getImage();  
        BufferedImage bimage = null;  
        GraphicsEnvironment ge = GraphicsEnvironment  
                .getLocalGraphicsEnvironment();  
        try {  
            int transparency = Transparency.OPAQUE;  
            GraphicsDevice gs = ge.getDefaultScreenDevice();  
            GraphicsConfiguration gc = gs.getDefaultConfiguration();  
            bimage = gc.createCompatibleImage(image.getWidth(null),  
                    image.getHeight(null), transparency);  
        } catch (HeadlessException e) {  
            // The system does not have a screen  
        }  
        if (bimage == null) {   
            // Create a buffered image using the default color model   
            int type = BufferedImage.TYPE_INT_RGB;   
            bimage = new BufferedImage (image.getWidth (null),   
                    image.getHeight (null), type);   
        }   
        / / Copy image to buffered image   
        Graphics g = bimage.createGraphics ();   
        // Paint the image onto the buffered image   
        g.drawImage (image, 0, 0, null);   
        g.dispose ();   
        return bimage;   
    }   
    / ** 
     * Get the base64 string of the picture by the URL of the picture 
     * @param imgUrl Picture url 
     * @return Returns the string of the base64 of the picture
     * / 
    public static String image2Base64(String imgUrl) {  

        URL url = null;   

        InputStream is = null;    

        ByteArrayOutputStream outStream = null;   

        HttpURLConnection httpUrl = null;   

        try {   

            url = new URL (imgUrl);   

            httpUrl = (HttpURLConnection) url.openConnection ();   

            httpUrl.connect ();   

            httpUrl .getInputStream ();   

            is = httpUrl.getInputStream ();             

              

            outStream = new ByteArrayOutputStream ();   

            // Create a Buffer string   

            byte [] buffer = new byte [1024];   

            // The length of each read string, if Is -1, which means all reads are completed   

            int len ​​= 0;  

            // Use an input stream to read data from the buffer  

            while ((len = is.read (buffer))! = -1) {   

                // Use the output stream to write data to the buffer, the middle parameter represents where to start reading, len represents the length of the   

                readoutStream.write (buffer , 0, len);   

            }   

            // Base64 encoding 

            return to byte array   Base64Util.encode (outStream.toByteArray ());   

        } catch (Exception e) {   

            e.printStackTrace ();   

        }   

        finally {   

            if (is! = Null)   

            {   

                try {   

                    is.close ();   

                } catch (IOException e) {   

                    e.printStackTrace ();   

                }   

            }  

            if(outStream != null)  

            {  

                try {  

                    outStream.close();  

                } catch (IOException e) {  

                    e.printStackTrace();  

                }  

            }  

            if(httpUrl != null)  

            {  

                httpUrl.disconnect();  

            }  

        }  

        return imgUrl;  

    }  
}    
Copy code

among them

The getBase64ByImgUrl method is obtained through Toolkit. As for why there is no comment, because I don't understand the principle, I copied it.
The image2Base64 method is by downloading a binary stream, which is of course copied. It is written to summarize. Next time you encounter the same problem, you do n’t have to check it everywhere. 
Attach the Base64Util code:
Copy code
 1 import java.io.ByteArrayOutputStream;
 2 import java.io.File;
 3 import java.io.IOException;
 4 import java.util.regex.Matcher;
 5 import java.util.regex.Pattern;
 6 
 7 import javax.imageio.stream.FileImageInputStream;
 8 
 9 import sun.misc.BASE64Decoder;
10 import sun.misc.BASE64Encoder;
11 
12 public class Base64Util{
13     /**
14      * 字符串转图片
15      * @param base64Str
16      * @return
17      */
18     public static byte[] decode(String base64Str){
19         byte[] b = null;
20         BASE64Decoder decoder = new BASE64Decoder();
21         try {
22             b = decoder.decodeBuffer(replaceEnter(base64Str));
23         } catch (IOException e) {
24             e.printStackTrace();
25         }
26         return b;
27     }
28     
29     /**
30      * 图片转字符串
31      * @param image
32      * @return
33      */
34     public static String encode(byte[] image){
35         BASE64Encoder decoder = new BASE64Encoder();
36         return replaceEnter(decoder.encode(image));
37     }
38     
39     public static String encode(String uri){
40         BASE64Encoder encoder = new BASE64Encoder();
41         return replaceEnter(encoder.encode(uri.getBytes()));
42     }
43     
44     /**
45      * 
46      * @path    图片路径
47      * @return
48      */
49     
50     public static byte[] imageTobyte(String path){
51         byte[] data = null;
52         FileImageInputStream input = null;
53         try {
54             input = new FileImageInputStream(new File(path));
55             ByteArrayOutputStream output = new ByteArrayOutputStream();
56             byte[] buf = new byte[1024];
57             int numBytesRead = 0;
58             while((numBytesRead = input.read(buf)) != -1){
59                 output.write(buf, 0, numBytesRead);
60             }
61             data = output.toByteArray();
62             output.close();
63             input.close();
64             
65         } catch (Exception e) {
66             e.printStackTrace();
67         }
68         
69         return data;
70     }
71     
72     
73     
74     public static String replaceEnter(String str){
75         String reg ="[\n-\r]";
76         Pattern p = Pattern.compile(reg);
77         Matcher m = p.matcher(str);
78         return m.replaceAll("");
79     }
80     
81     
82 }
Copy code

Guess you like

Origin www.cnblogs.com/Anonyme/p/12704304.html