简体   繁体   English

Java从URL读取JPG文件

[英]Java Read JPG File From URL

public class Socket {
    public Socket() {
        try {
            URL url = new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg");
            InputStream in = url.openStream();
            BufferedInputStream bin = new BufferedInputStream(in); 


            ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
            byte[] okunan = new byte[4096];

            while(in.read()!= -1){
                bout.write(okunan, 0, in.read());

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I got this error: Exception in thread "main" java.lang.IndexOutOfBoundsException at java.io.ByteArrayOutputStream.write(Unknown Source) 我收到此错误:线程“主”中的异常java.io.ByteArrayOutputStream.write处的java.lang.IndexOutOfBoundsException(未知源)

I want to read this jpeg file to in bytearrayoutputstream after then write to file. 我想将这个jpeg文件读取到bytearrayoutputstream之后,然后写入文件。

Sory for my bad english.. 对不起,我的英语不好。

尝试这个

BufferedImage img = ImageIO.read(new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg"));

Use the ImageIO API 使用ImageIO API

BufferedImage img = ImageIO.read(new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg"));

ByteArrayOutputStream bout = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", bout);

Check this and this for info 检查以获得信息

Do you mean something like 你的意思是

try {
        URL url = new URL("http://images2.layoutsparks.com/1/56178/castle-stone-window-grey.jpg");
        InputStream in = url.openStream();
        BufferedInputStream bin = new BufferedInputStream(in); 


        ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
        byte[] okunan = new byte[4096];

        while(in.read()!= -1){
            in.read(okunan);
            bout.write(okunan);

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Use javax.imageio.ImageIO rather than simple InputStream of java.io package. 使用javax.imageio.ImageIO而不是java.io包的简单InputStream。

Have a look here, I think it will be helpful: 在这里看看,我认为这会有所帮助:

http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM