【问题标题】:Picasso Image in Database数据库中的毕加索图像
【发布时间】:2018-02-07 08:06:45
【问题描述】:

我有一个简单的问题。如何将毕加索图像(从 json 成功加载)保存到数据库中。如果可能的话,我想将其转换为位图,还是有其他方法可以保存它? 我尝试了这种可绘制图像的方法,并且效果很好。

我的代码:

public static byte[] imageViewToByte(ImageView image) {
    Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
    // Bitmap bitmap=(BitmapDrawable)image.getI);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;`.   
}

【问题讨论】:

  • Picasso中有一个图片加载回调监听器。当您的图像完全下载时,您将获得 Bitmap 对象,该对象将是您加载的图像位图并将其保存到数据库。
  • 通常将实际图像存储在数据库中是一种不好的做法,但其 Uri 除外。图像应保留为文件而不是 BLOB。
  • 我的图片是从 json 加载的,那么我该如何保存呢。

标签: java android sqlite android-studio picasso


【解决方案1】:

成功加载图片设置为毕加索后,使用以下代码将图片网址转换为位图:

 try {
    URL url = new URL("http://....");
    Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
    System.out.println(e);
}

或者,在下面使用:

public static Bitmap getBitmapFromURL(String src) {
try {
    URL url = new URL(src);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.connect();
    InputStream input = connection.getInputStream();
    Bitmap myBitmap = BitmapFactory.decodeStream(input);
    return myBitmap;
} catch (IOException e) {
    e.printStackTrace();
    return null;
}
}

通过sharedpreference,您可以将位图保存到内部存储中。

【讨论】:

  • 我想在 sqlliteopenhelper 的帮助下保存它而不是我该怎么做我在 json 中传递图像的链接图像从 json 加载
  • @sajidamin,如果您要保存图像,那么当您在没有互联网的情况下从数据库中检索图像时,但是如果您要保存 url,那么您必须再次使用 picasso 和互联网
  • 简单我想将图像保存在收藏夹中以供收藏,我创建了一个数据库,在数据库中我想传递字节数组。正如我上面提到的,该方法成功地适用于可绘制的图像,但对于从 json 加载的毕加索图像它不起作用。我想将此毕加索图像转换为字节数组并传递给数据库
  • @sajidamin ,请告诉我问题,你想做什么?
  • 我有一个带有图像 url 和其他数据的 json 文件...当用户单击此收藏按钮时,我有一个收藏按钮,数据已成功存储在数据库中,现在一切正常,但图像是从毕加索加载并在数据库中我想保存这张毕加索图像如何将这张毕加索图像转换为字节数组以将其保存到数据库中。
猜你喜欢
  • 1970-01-01
  • 2018-07-29
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 2014-08-29
  • 2014-04-10
相关资源
最近更新 更多