java - 读取图像并通过套接字发送 - 无法打开文件

标签 java image sockets image-processing

我正在尝试编写一个简单的服务器,它使用套接字并在收到来自浏览器的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/

相关文章:

java - ArrayList的值在匿名内部类之外是不同的

java - 在 java 中编辑 MS Lync 对话聊天

html - 以 HTML 格式在图片上可见的文本

html - jpg 图像未在 HTML 中呈现

javascript - 有没有办法在浏览器中显示图像而无需在开发人员工具中预览图像?

java - 在Gradle构建脚本中使用Scala(或Java)方法

java - 执行 Java 自动导入的控制台命令

sockets - 在 goroutines 中使用套接字的正确方法是什么

java - 使用套接字时如何处理消息被破坏的情况?

linux - linux 中的 ip_rcv 函数在哪里?