繁体   English   中英

如何在Android应用中离线使用图片?

[英]How to make images available offline in an android app?

我有一个应用程序,即使没有互联网,我也需要用户查看图像。 最初,我向mysql数据库发出凌空请求,然后使用解析的数据通过Picasso显示图像。

Picasso.with(context).load(magazineVersions.get(position).getMagazine_image_url()).resize(400, 500).into(holder.iv_magazine);  

现在,我还根据我的截击请求下载图像,并将它们存储在名为.images的文件夹中,如下所示:-

public ArrayList showJSON(String json) {
    ParseJSON pj = new ParseJSON(json);
    pj.parseJSON();

    image_url = ParseJSON.img_url;
    mag_version = ParseJSON.magversion;
    download_path = ParseJSON.download_url;
    sample_url = ParseJSON.sample_url;

    for (String img : image_url) {
        downloadImages(img);
    }

    ArrayList android_version = new ArrayList<>();

    for (int i = 0; i < image_url.length; i++) {
        MagazineVersion magazineVersion = new MagazineVersion();
        magazineVersion.setMagazine_version_name(mag_version[i]);
        magazineVersion.setMagazine_image_url(image_url[i]);
        magazineVersion.setDownload_url(download_path[i]);
        magazineVersion.setSample_url(sample_url[i]);
        android_version.add(magazineVersion);
    }
    return android_version;
}

downloadImages的代码如下:-

public void downloadImages(String img_url) {
    String fileName = img_url.substring(img_url.lastIndexOf('/') + 1, img_url.length());
    File file = new File("/storage/emulated/0/.shatayushi/.images" + fileName);

    if (file.exists() && !file.isDirectory()) {
        Log.d("ImageExists", fileName);

    }else
        new DownloadImagesAsync().execute(img_url);
}

我想知道如何使用下载的图像而不是存储在服务器上的图像。

if(Images exist in .images folder)
{
    //use picasso to display the images stored in the device 
}else
{
    //use picasso to display the images stored on the server
Picasso.with(context).load(magazineVersions.get(position).getMagazine_image_url()).resize(400, 500).into(holder.iv_magazine);
}

使用了Android Universal Image-Loader,这是存储在缓存中的最佳图像

宣布

    private ImageLoader imageLoader1;

创建时

 imageLoader1 = ImageLoader.getInstance();

 imageLoader1.init(ImageLoaderConfiguration.createDefault(getActivity()));

no_image这里是可绘制的图像,缓存中未加载任何图像

   DisplayImageOptions
            options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .showImageOnLoading(R.drawable.no_image) // resource or drawable
            .showImageForEmptyUri(R.drawable.no_image) // resource or drawable
            .showImageOnFail(R.drawable.no_image)
            .considerExifParams(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    imageLoader1.displayImage(yourpath.replace(" ", "%20"), ivprofile, options);

您也可以将Piccaso用于此缓存中的存储图像,也可以用于okhttp ...用于此...

 if (imageURL != null) {
Picasso.with(this).load(imageURL).error(R.drawable.no_Image)
.into(ivImage);
}

也可以用Okhttp编译。

暂无
暂无

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

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