我有一个要求,我想从用户那里获取图像的URL,然后将其转换为字节格式,并将其发送到我的服务器,我使用tomcat作为Web应用程序服务器,使用hibernate作为ORM工具,我已经编写了服务器端代码用于使用 BLOB 将传入字节保存到表中,但我的问题是如何将图像转换为字节数组,以便我可以将数组发送到服务器以进一步处理。
添加到上面,我可以从表加载数据,然后可以将字节发送回客户端,但如何将字节转换回图像。
目前,我在客户端使用 HTML 来处理网页,并使用 Servlet 来处理请求和响应。
请帮助我。
最佳答案
如果是图像 URL,则只需将 URL 直接读取到字节数组中,如下所示:
public static byte[] getBytesFromURL(URL url) throws IOException {
InputStream in = null;
ByteArrayOutputStream out = null;
try {
in = url.openStream();
out = new ByteArrayOutputStream();
int len;
byte[] buf = new byte[1024 * 4];
while ((len = in.read(buf)) >= 0) {
out.write(buf, 0, len);
}
byte[] bytes = out.toByteArray();
return bytes;
} catch (IOException e) {
throw e;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
关于java - 在java中获取图像的字节格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4024610/