java数组缓冲_java-如何将字节数组转换为缓冲的图像

我有一个从客户端获取字节数组的服务器端Java代码.为了进行一些图像处理,我需要将字节数组转换为BufferedImage.我有一个应该在这里执行的代码:

public void processImage(byte[] data) {

ByteArrayInputStream stream = new ByteArrayInputStream(data);

BufferedImage bufferedImage;

bufferedImage = ImageIO.read(stream);

// bufferedImage is null

//...

}

但这是行不通的. bufferedImage为null.根据ImageIO文档:

If no registered ImageReader claims to be able to read the resulting stream, null is returned.

我如何告诉ImageReader它是什么图像类型.例如,如果我知道图像是JPEG(在我的情况下就是JPEG),我应该怎么做?

编辑:感谢您的建议,该文件很可能不是JPEG格式.这是我拥有的客户端代码,用于将数据作为String发送到服务器:

import org.json.JSONObject;

// Client-side code that sends image to server as String

public void sendImage() {

FileInputStream inputStream = new FileInputStream(new File("myImage.jpg"));

ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

byte[] b = new byte[1024];

while ((bytesRead = inputStream.read(b)) != -1) {

byteStream.write(b,0,bytesRead);

}

byte[] byteArray = byteStream.toByteArray();

JSONObject jsonObject = new JSONObject();

jsonObject.put("data",new String(byteArray));

// ... more code here that sends jsonObject in HTTP post body

}

这是调用processImage()函数的服务器端代码:

// Server-side code that calls processImage() function

public void handleRequest(String jsonData) {

JSONObject jsonObject = new JSONObject(jsonData);

processImage(jsonObject.getString("data").getBytes());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值