下载图片,保存到商店,但图片库无法看到该图片

时间:2017-03-22 00:04:29

标签: android image bitmap save gallery

我正在制作从服务器下载图像的画廊应用程序并放入app文件夹。但是当我打开这个应用程序(https://play.google.com/store/apps/details?id=com.sonyericsson.album)时,我无法看到我的下载图像。这是我的代码 下载图片:

Glide.with(getActivity()).load(path)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(final Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            Log.d(TAG, "pamti se");
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    saveToDirectory(resource, path);
                                }
                            }, 0);

                        }

                    });

保存到目录:

private void saveToDirectory(Bitmap bitmap, String path) {
    File pictureFile = getOutputMediaFile(path);
    if (pictureFile == null) {
        Toast.makeText(getActivity(), "Došlo je do greške!", Toast.LENGTH_LONG).show();
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    }
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.close();
        Toast.makeText(getActivity(), "Slika je sačuvana!", Toast.LENGTH_LONG).show();
    } catch (FileNotFoundException e) {
        Toast.makeText(getActivity(), "Došlo je do greške!", Toast.LENGTH_LONG).show();
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Toast.makeText(getActivity(), "Došlo je do greške!", Toast.LENGTH_LONG).show();
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }
}

@Nullable
private File getOutputMediaFile(String path) {
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), getActivity().getString(R.string.app_name));
    Log.d(TAG, mediaStorageDir.getAbsolutePath());

    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }
    String name = "";
    for(int i = path.length() - 1; i >= 0; i--) {
        if (path.charAt(i) == '/') {
            break;
        }
        name = path.charAt(i) + name;
    }

    File mediaFile;
    String mImageName = getActivity().getString(R.string.app_name) +"_"+ name;
    //String mImageName = "IMG" +"-"+ name;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
    return mediaFile;
}

2 个答案:

答案 0 :(得分:2)

您要将图片保存到内部应用程序存储空间,您需要将其提供给图库(应用程序的外部存储空间)才能在应用程序外部使用。

试试这个方法:

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    //change mCurrentPhotoPath for your imagepath
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

参考文件:

https://developer.android.com/training/camera/photobasics.html#TaskGallery

https://developer.android.com/guide/topics/data/data-storage.html#filesExternal

答案 1 :(得分:0)

第1步。

将文件保存到Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)

第2步。 使用MediaScanner通知系统有关新文件/图像的信息。我为此创建了一个帮助类。您所要做的就是传递文件路径:

import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.lang.ref.WeakReference;

public class MediaScannerUtils implements
        MediaScannerConnection.MediaScannerConnectionClient {

    private static final String LOG_TAG = "MediaScannerUtils";

    private MediaScannerConnection mConnection;
    private @Nullable WeakReference<MediaScannerListener> mListenerRef;
    private String mPathToScan;
    private String mMimeType;

    /**
     * Initialize the MediaScannerUtils class
     * @param context Any context
     * @param listener A listener that gets notified when the scan is completed
     * @param pathToScan The path to scan. If null, the entire sdcard is scanned
     * @param mimeType The mimeType of files to look for. If null, defaults to "audio/*"
     */
    public MediaScannerUtils(@NonNull Context context, @Nullable MediaScannerListener listener,
                             @Nullable String pathToScan, @Nullable String mimeType) {
        LogUtils.d(LOG_TAG, "Initializing MediaScannerUtils");
        mPathToScan = pathToScan;
        mMimeType = mimeType;
        if(pathToScan == null) {
            //If path to scan is null, set path to the entire SdCard
            mPathToScan = FileUtils.getSDCardAbsolutePath();
        }
        if(mimeType == null) {
            //If mime type is null, set mime type to audio wildcard
            mMimeType = "image/*";
        }

        if(listener != null) {
            mListenerRef = new WeakReference<>(listener);
        }

        mConnection = new MediaScannerConnection(context.getApplicationContext(), this);
        mConnection.connect();
    }

    /**
     * Called to notify the client when a connection to the
     * MediaScanner service has been established.
     */
    public void onMediaScannerConnected() {
        mConnection.scanFile(mPathToScan, mMimeType);
    }

    /**
     * Called to notify the client when the media scanner has finished
     * scanning a file.
     * @param path the path to the file that has been scanned.
     * @param uri the Uri for the file if the scanning operation succeeded
     * and the file was added to the media database, or null if scanning failed.
     */
    public void onScanCompleted(String path, Uri uri) {
        if(mConnection != null) {
            mConnection.disconnect();
        }

        if(mListenerRef != null) {
            MediaScannerListener listener = mListenerRef.get();
            if (listener != null) {
                listener.onScanCompleted();
            }
        }
    }

    /**
     * Disconnects the MediaScannerConnection and releases any heavy object
     */
    public void release() {
        if (mConnection != null) {
            mConnection.disconnect();
            mConnection = null;
        }
    }

    public interface MediaScannerListener {

        void onScanCompleted();

    }
}