简体   繁体   中英

How to convert loaded bytes into image without ImageIO.read()

I can't use ImageIO.read() because of my own restrictions. I can only load bytes after GET request and I need to save this bytes to file as image. But it seems to me, that there also loads some extra data, which browser usually filter (maybe response headers). So I get the array of raw bytes which I even can't open as image.

What should I do with this bytes?

Example:

byte[] buf = ContentLoader.loadBytes(new URL("http://images.visitcanberra.com.au/images/canberra_hero_image.jpg"));
try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\image.jpg"));
            fileOutputStream.write(buf);
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

loadBytes() method:

public static byte[] loadBytes(URL url) {
        ByteArrayOutputStream boutArray = new ByteArrayOutputStream();
        try {
            URLConnection connection = url.openConnection();
            BufferedInputStream bin = new BufferedInputStream(connection.getInputStream());
            byte[] buffer = new byte[1024 * 16];
            while (bin.read(buffer) != -1) {
                boutArray.write(buffer);
                boutArray.flush();
            }
            bin.close();
        } catch (Exception e) {
            return null;
        }
        return boutArray.toByteArray();
    }

Usual problems. The standard way to copy a stream in Java is:

int count;
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}
out.close();
in.close();

Note that you need to store the result returned by read() into a variable; that you need to use it in the next write() call; that you shouldn't flush() inside a loop; and that you need to close the input and output streams.

And why you're using a ByteArrayInputStream at all is a mystery. It's just a waste of time and space. Read directly from the URL input stream, and write directly to the FileOutputStream .

The following code works for me:-

    URL url = new URL("my url...");
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream("img.jpg");

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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