Why can't I read an image from a byte array?

When I use ImageIO.read(URL), I get the image without any problems, but if I read bytes from the link in my own way, write them to an array and then try to convert them into an image, the ImageIO.read(ByteArrayInputStream) method returns null.

Here's my code:
private URLResponse buildResponse(HttpURLConnection connection) throws IOException {
    int responseCode = connection.getResponseCode();

    HashMap<String, String> headers = new HashMap<>();
    for (Map.Entry<String, java.util.List<String>> headerEntry : connection.getHeaderFields().entrySet()) {
        headers.put(headerEntry.getKey(), String.join(",", headerEntry.getValue()));
    }

    ByteArrayOutputStream baos;
    if("45".contains(String.valueOf(responseCode).substring(0, 1))) {
        baos = readStream(connection.getErrorStream());
    }else{
        baos = readStream(connection.getInputStream());
    }
    return new URLResponse(responseCode, baos.toByteArray(), headers);
}

private ByteArrayOutputStream readStream(InputStream inputStream) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[4096];
    int len;
    while ((len = (byte) inputStream.read(buff)) > 0) {
        baos.write(buff, 0, len);
    }
    return baos;
}

public record URLResponse(int code, byte[] bytes, HashMap<String, String> headers) implements Serializable{
    @Serial
    private static final long serialVersionUID = 1L;
    public String response(){
        return new String(bytes);
    }
    public <T> T json(Class<T> clazz) {
        return Launch.gson.fromJson(response(), clazz);
    }
    public BufferedImage image() throws IOException {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(bytes));
        if(bi == null){
            throw new NullPointerException("Image is null");
        }
        return bi;
    }
}


JDK: open jdk 21
Was this page helpful?