我正在尝试编写一个简单的服务器,它使用套接字并在收到来自浏览器的http请求时从光盘读取图像。
我能够接收请求,从光盘读取图像并将其传递到浏览器(然后浏览器自动下载图像)。但是,当我尝试打开下载的图像时,它显示:
Could not load image 'img.png'. Fatal error reading PNG image file: Not a PNG file
所有其他类型的扩展名(jpg、jpeg、gif 等...)也是如此
你能帮帮我并告诉我我做错了什么吗?我怀疑我读取图像的方式可能有问题,或者可能必须指定某些编码?
从光盘读取图像:
// 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();
}
通过套接字写入数据:
OutputStream output = clientSocket.getOutputStream();
output.write(result);
在本例中,结果包含 readImage 方法生成的字节数组。
编辑:第二次尝试将图像作为普通文件读取
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();
最佳答案
您可以使用 ByteArrayOutputStream,例如,
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", byteArrayOutputStream);
然后你可以向套接字写入,
outputStream.write(byteArrayOutputStream.toByteArray());
关于java - 读取图像并通过套接字发送 - 无法打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29668566/