jeudi 16 avril 2015

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.


Thanks for any tips!


Aucun commentaire:

Enregistrer un commentaire