简体   繁体   English

Android-从URL获取,保存和检索图像

[英]Android - Getting, saving and retrieving images from URL

I have a database of recipes, each of which has an image. 我有一个配方数据库,每个配方都有一个图像。

The database can be updated from a JSON feed. 可以从JSON feed更新数据库。 I then need to retrieve any new images for a newly added recipe. 然后,我需要检索新添加的食谱的任何新图像。 I'm having issues getting an image from a URL, saving it and then updating a recipe with that image. 我在从URL获取图像,保存图像,然后用该图像更新配方时遇到问题。

There are a lot of different answers on Stack Overflow and other sites. Stack Overflow和其他站点上有很多不同的答案。 Often I can get to what I would expect to be a working point. 通常,我可以达到我期望的工作点。 Where images appear to be getting saved, and any debug print outs I add in show what I expect, but I cannot update my ImageView. 似乎要保存图像的位置以及我添加的所有调试打印输出均显示了预期的效果,但无法更新ImageView。 By that I mean it remains blank. 我的意思是,它仍然是空白。

I'm not sure if my issue is simply a poor attempt to update the ImageView, or a problem when saving the images. 我不确定我的问题是否只是尝试更新ImageView的错误尝试,还是保存图像时出现的问题。 This code is a bit sloppy and inefficient at the moment. 此代码目前有点草率和低效。 I've tried 10-15 variations on this from suggested other posts and have had no luck. 我已经从其他建议的帖子中尝试了10-15个变体,但没有运气。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Manifest 表现

/* I have these two set (Not sure both are necessary) */
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Main frontend class 主要前端类

/* Create databaseHelper */
DatabaseHelper db = new DatabaseHelper(getApplicationContext());

/* ImageView to update image of */
ImageView foodpic = (ImageView)findViewById(R.id.foodpic);

/* Check if image is already available in drawable folder */
int resID = this.getResources().getIdentifier(filename, "drawable", "mypackage.name");
if (resID == 0) {
    /* If not, call function to retrieve from external storage */
    newPic = db.getOutputMediaFile(origFilename);

    if(newPic.exists()) {
        myBitmap = BitmapFactory.decodeFile(newPic.getAbsolutePath());
        foodpic.setImageBitmap(myBitmap);
        foodpic.invalidate(); /* Tried with and without this */
    }
}

DatabaseHelper function to retrieve image saved from URL DatabaseHelper函数检索从URL保存的图像

public File getOutputMediaFile(String filename){
    /* Dir I'm (attempting) to save and retrieve images from */
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/mypackage.name/Files"); 

    /* Create the storage directory if it does not exist */
if (! mediaStorageDir.exists()){
    if (! mediaStorageDir.mkdirs()){
        return null;
    }
}

    /* Get file extension */
    String[] fileNameSplit = filename.split("\\.");
String extension = fileNameSplit[(fileNameSplit.length-1)];

    /* Get filename, remove special chars & make lowercase */
int extensionIndex = filename.lastIndexOf(".");
filename = filename.substring(0, extensionIndex);
filename = filename.toLowerCase(Locale.getDefault());
filename = filename.replaceAll("[^a-z0-9]", "");

    /* Re-make filename to save image as */
    String mImageName="r"+filename+"."+extension;

    /* Get file 
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
    return mediaFile;
}

DatabaseHelper function to save image from URL - Called per recipe/image added to the database, if image not found in drawable folder. DatabaseHelper函数可从URL保存图像 -如果在可绘制文件夹中找不到图像,则按添加到数据库中的每个配方/图像调用。

public static void saveImage(String imageUrl, String destinationFile, String extension) throws IOException {

URL url = new URL (imageUrl);
InputStream input = url.openStream();
try {
    File storagePath = Environment.getExternalStorageDirectory();
    OutputStream output = new FileOutputStream (new File(storagePath,destinationFile));
    try {
        byte[] buffer = new byte[2048];
        int bytesRead = 0;
    while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
        output.write(buffer, 0, bytesRead);
            }
    } finally {
    output.close();
}
} finally {
    input.close();
}

*Formatting. *格式化。

Store URL as string in DB and display it with Image Loader is more easy, but doesn't work off line ,if ur apps need internet to work, the image loader could be better. 将URL作为字符串存储在DB中,并使用Image Loader显示它更容易,但是不能离线运行,如果您的应用需要互联网才能工作,则Image loader可能更好。 android-loading-image-from-url-http Android的加载图像,从-URL-HTTP

I ended up using this library. 我最终使用了这个库。

It's not an ideal solution as I'd have preferred to look through this library, understand it fully and explain it for others who may need a similar answer. 这不是一个理想的解决方案,因为我希望仔细阅读该库,对其进行全面了解,并为可能需要类似答案的其他人进行解释。 But for now, people attempting to do something similar should be able to use this too. 但是现在,尝试做类似事情的人也应该可以使用它。

https://code.google.com/p/imagemanager/ https://code.google.com/p/imagemanager/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM