Smajl
Smajl

Reputation: 7995

Read image and send it via socket - could not open file

I am trying to write a simple server that uses sockets and reads images from disc when it receives http request from browser.

I am able to receive the request, read the image from disc and pass it to the browser (the browser then automatically downloads the image). However, when I try to open the downloaded image, it says:

Could not load image 'img.png'. Fatal error reading PNG image file: Not a PNG file

The same goes for all other types of extensions (jpg, jpeg, gif etc...)

Could you help me out and tell me what am I doing wrong? I suspect that there might be something wrong with the way I read the image or maybe some encoding has to be specified?

Reading the image from disc:

    // read image and serve it back to the browser
    public byte[] readImage(String path) {
        File file = new File(FILE_PATH + path);

        try {
            BufferedImage image = ImageIO.read(file); // try reading the image first
            // get DataBufferBytes from Raster
            WritableRaster raster = image.getRaster();
            DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
            return data.getData();
        } catch (IOException ex) {
            // handle exception...
        }

        return ("Could not read image").getBytes();
    }

Writing the data via socket:

OutputStream output = clientSocket.getOutputStream();
output.write(result);

In this case, the result contains the byte array produced by the readImage method.

EDIT: second try with reading the image as normal file

FileReader reader = new FileReader(file);
char buf[] = new char[8192];
int len;
StringBuilder s = new StringBuilder();
while ((len = reader.read(buf)) >= 0) {
     s.append(buf, 0, len);
     byte[] byteArray = s.toString().getBytes();
}

return s.toString().getBytes();

Upvotes: 0

Views: 717

Answers (1)

Paritosh
Paritosh

Reputation: 535

You may use ByteArrayOutputStream, like,

 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 ImageIO.write(image, "jpg", byteArrayOutputStream);

and then you can write to socket as,

 outputStream.write(byteArrayOutputStream.toByteArray());

Upvotes: 2

Related Questions