从网络获取图片

  从网络获取图片链接地址后,我们首先要判断是否图片链接,再去请求图片资源,但其实我们取到的是文件资源,还是不能确定是图片,所以还需要再校验一次:

public static void main(String[] args) throws IOException
    {
        String imageUrl = "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg";
        
        // 第一次校验链接地址后缀
        if (!imageUrl.matches(".+(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.PNG|.png)$"))
        {
            System.out.println("you are wrong imageUrl.");
        }
        else
        {
            System.out.println("you are right imageUrl.");
            
            // 根据网络地址获得图片的输入流
            URL image = new URL(URLDecoder.decode(imageUrl, "UTF-8"));
            HttpURLConnection conn = (HttpURLConnection)image.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            
            // 第二次判断是否图片文件
            BufferedImage imageIO = ImageIO.read(inStream);
            if(imageIO == null)
            {
                System.out.println("you are not image");
            }
            else
            {
                System.out.printf("the image' width is %s, height is %s.",imageIO.getWidth(),imageIO.getHeight());
            }
        }
    }

  我这里的链接真是图片,所以执行结果:

you are right imageUrl.
the image' width is 620, height is 927.

   如果图片比较特殊,或者图片链接是https开头的,那么校验机制就有问题了。这里再列举下这种情况下的校验,而且我们把图片转为输入流,后面可以拿它去上传的:

public static void main(String[] args) throws IOException
    {
        String imageUrl =
            "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83epDm5wVghs1TRrCkNhYBBANofLBYmCVAUk858Bo63VWsxTEdflZXFOFnI5dhP0libnCPBVv7Hhyx8Q/132";
        
        // 网络链接地址转临时输入流
        InputStream tempStream = null;
        URL image = new URL(URLDecoder.decode(imageUrl, "UTF-8"));
        BufferedImage bufferedImage = null;
        // 根据网络地址获得图片的输入流,并读取图片
        if (null != image)
        {
            bufferedImage = ImageIO.read(image.openStream());
        }
        
        // 判断是否图片
        if (bufferedImage == null)
        {
            System.out.println("you are not image");
        }
        
        // 将图片转为jpg格式的输出流,再把输出流转为输入流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", baos);
        tempStream = new ByteArrayInputStream(baos.toByteArray());
    }
原文地址:https://www.cnblogs.com/wuxun1997/p/9932097.html