【问题标题】:How to I retrieve an image from a URL and store it as a Blob in Java (google app engine)如何从 URL 中检索图像并将其存储为 Java 中的 Blob(谷歌应用引擎)
【发布时间】:2011-01-26 10:13:14
【问题描述】:

我了解如何获取 URL 文本页面并遍历结果

URL url = new URL(this.url);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
    ....

如何获取图像并将其存储为 Blob?

【问题讨论】:

    标签: java google-app-engine jdbc blob


    【解决方案1】:

    直接使用InputStream 并使用PreparedStatement#setBinaryStream() 存储它。它是二进制数据,而不是字符数据,所以 Reader 只会搞砸事情,你不想拥有它。

    简而言之:

    InputStream input = imageUrl.openStream();
    
    // ...
    
    statement = connection.prepareStatement("INSERT INTO image (content) VALUES (?)");
    statement.setBinaryStream(1, input);
    statement.executeUpdate();
    

    PreparedStatement 真的很有用。它不仅使您免于使用SQL injections,而且还简化了在SQL 语句中设置像InputStream 这样的完全有价值的Java 对象。您可以在JDBC tutorial 了解有关PreparedStatement 的更多信息。

    【讨论】:

    • 谢谢,我在 InputStream 方面取得了更多进展,但是,由于我使用的是 Google App Engine,我需要将 Blob 存储到对象的属性中。您能否阐明我如何将 InputStream 转换为 Blob?
    • 你为什么要这样做?只需使用PreparedStatement#setBinaryStream()InputStream 存储到DB blob 字段中,然后使用ResultSet#getBinaryStream() 从DB blob 字段中检索InputStream。无需为 java.sql.Blob 或 Java 代码中类似的紧耦合内容而烦恼。
    • 感谢您的帮助,我缺少的一点是 byte[] theBytes = new byte[input.available()]; input.read(theBytes);
    • 麻烦!! 1) 不要将其存储为byte[],它会占用内存,请坚持使用InputStream。 2) 不要使用input.available(),它只是返回可供读取的下一个字节而不阻塞流,它并不表示完整的内容长度(但可能巧合在小文件的情况下)。
    • 感谢您的建议。我很快就放弃了这种思路,但下次我会保留你的提示。
    【解决方案2】:

    好吧,我存储二进制数据(例如图像)的方法非常简单。就我而言,我处理上传到 servlet 的文件。在 servlet 内部,我使用 request.getInputStream() 在发布的正文上获取 InputStream。但是,这适用于任何类型的 InputStreawm,包括基于 URL 的 InputStreawm。下面的示例代码展示了如何将该 InputStream 转换为 google appeninge Blob,然后您可以将其持久保存在数据存储中。

    ...
    import org.apache.commons.io.IOUtils;
    import com.google.appengine.api.datastore.Blob;
    ...
    
    public void InputStreamToBlob(InputStream i) throws IOException {
    
        ...
    
        Blob content = new Blob(IOUtils.toByteArray(i));
        ...
    

    【讨论】:

      【解决方案3】:

      对于图像,不是逐行读取缓冲区,而是将其加载到字节数组中,并将此字节数组保存为 blob。

      【讨论】:

      • 这也是可能的,只是可能比使用InputStream更占用内存。
      猜你喜欢
      • 2011-11-21
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 2011-02-23
      • 2010-12-03
      • 2012-03-03
      • 1970-01-01
      相关资源
      最近更新 更多