android - 将图像保存到图库中

Chr*_*oni 83 android gallery save-image imageview

我有一个带有图片库的应用程序,我希望用户可以将其保存到自己的图库中.我已经创建了一个带有单个声音"保存"的选项菜单,但问题是......我怎样才能将图像保存到图库中?

这是我的代码:

@Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle item selection
            switch (item.getItemId()) {
            case R.id.menuFinale:

                imgView.setDrawingCacheEnabled(true);
                Bitmap bitmap = imgView.getDrawingCache();
                File root = Environment.getExternalStorageDirectory();
                File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
                try 
                {
                    file.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(file);
                    bitmap.compress(CompressFormat.JPEG, 100, ostream);
                    ostream.close();
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }



                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }
Run Code Online (Sandbox Code Playgroud)

我不确定这部分代码:

File root = Environment.getExternalStorageDirectory();
                File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
Run Code Online (Sandbox Code Playgroud)

保存到画廊是否正确?不幸的是代码不起作用:(

sfr*_*ini 161

MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Run Code Online (Sandbox Code Playgroud)

前面的代码将在图库的末尾添加图像.如果要修改日期以使其显示在开头或任何其他元数据,请参阅下面的代码(SK的Cortesy,samkirton):

https://gist.github.com/samkirton/0242ba81d7ca00b475b9

/**
 * Android internals have been modified to store images in the media folder with 
 * the correct date meta data
 * @author samuelkirton
 */
public class CapturePhotoUtils {

    /**
     * A copy of the Android internals  insertImage method, this method populates the 
     * meta data with DATE_ADDED and DATE_TAKEN. This fixes a common problem where media 
     * that is inserted manually gets saved at the end of the gallery (because date is not populated).
     * @see android.provider.MediaStore.Images.Media#insertImage(ContentResolver, Bitmap, String, String)
     */
    public static final String insertImage(ContentResolver cr, 
            Bitmap source, 
            String title, 
            String description) {

        ContentValues values = new ContentValues();
        values.put(Images.Media.TITLE, title);
        values.put(Images.Media.DISPLAY_NAME, title);
        values.put(Images.Media.DESCRIPTION, description);
        values.put(Images.Media.MIME_TYPE, "image/jpeg");
        // Add the date meta data to ensure the image is added at the front of the gallery
        values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
        values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());

        Uri url = null;
        String stringUrl = null;    /* value to be returned */

        try {
            url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            if (source != null) {
                OutputStream imageOut = cr.openOutputStream(url);
                try {
                    source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
                } finally {
                    imageOut.close();
                }

                long id = ContentUris.parseId(url);
                // Wait until MINI_KIND thumbnail is generated.
                Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
                // This is for backward compatibility.
                storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
            } else {
                cr.delete(url, null, null);
                url = null;
            }
        } catch (Exception e) {
            if (url != null) {
                cr.delete(url, null, null);
                url = null;
            }
        }

        if (url != null) {
            stringUrl = url.toString();
        }

        return stringUrl;
    }

    /**
     * A copy of the Android internals StoreThumbnail method, it used with the insertImage to
     * populate the android.provider.MediaStore.Images.Media#insertImage with all the correct
     * meta data. The StoreThumbnail method is private so it must be duplicated here.
     * @see android.provider.MediaStore.Images.Media (StoreThumbnail private method)
     */
    private static final Bitmap storeThumbnail(
            ContentResolver cr,
            Bitmap source,
            long id,
            float width, 
            float height,
            int kind) {

        // create the matrix to scale it
        Matrix matrix = new Matrix();

        float scaleX = width / source.getWidth();
        float scaleY = height / source.getHeight();

        matrix.setScale(scaleX, scaleY);

        Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
            source.getWidth(),
            source.getHeight(), matrix,
            true
        );

        ContentValues values = new ContentValues(4);
        values.put(Images.Thumbnails.KIND,kind);
        values.put(Images.Thumbnails.IMAGE_ID,(int)id);
        values.put(Images.Thumbnails.HEIGHT,thumb.getHeight());
        values.put(Images.Thumbnails.WIDTH,thumb.getWidth());

        Uri url = cr.insert(Images.Thumbnails.EXTERNAL_CONTENT_URI, values);

        try {
            OutputStream thumbOut = cr.openOutputStream(url);
            thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
            thumbOut.close();
            return thumb;
        } catch (FileNotFoundException ex) {
            return null;
        } catch (IOException ex) {
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这可以保存图像,但是到了画廊的末端,但是当你用相机拍照时,它会保存在最顶层.如何将图像保存到图库顶部? (22认同)
  • 请注意,您还必须在manifestxt.xml中添加<uses-permission android:name ="android.permission.WRITE_EXTERNAL_STORAGE"/>. (19认同)
  • [这是上面提到的正确的GIST链接](https://gist.github.com/samkirton/0242ba81d7ca00b475b9)(需要在末尾删除`.git`) (6认同)
  • 图像不会保存在图库的顶部,因为内部insertImage不会添加任何日期元数据.请参阅此GIST:https://gist.github.com/0242ba81d7ca00b475b9.git它是insertImage方法的精确副本,但它添加了日期元日期以确保图像添加到库的前面. (3认同)
  • ```MediaStore.Images.Media.insertImage(...)``` 已被弃用。 (3认同)
  • 如何更改文件夹名称? (2认同)

Sig*_*ist 46

实际上,你可以在任何地方保存你的照片.如果要保存在公共空间中,任何其他应用程序都可以访问,请使用以下代码:

storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    ), 
    getAlbumName()
);
Run Code Online (Sandbox Code Playgroud)

图片没有进入专辑.为此,您需要调用扫描:

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}
Run Code Online (Sandbox Code Playgroud)

您可以在https://developer.android.com/training/camera/photobasics.html#TaskGallery找到更多信息

  • 当您仅扫描以下文件时,发送广播可能会浪费资源:http://stackoverflow.com/a/5814533/43051。 (2认同)
  • 你实际上在哪里传递位图? (2认同)
  • ```Environment.getExternalStoragePublicDirectory``` 和 ```Intent.ACTION_MEDIA_SCANNER_SCAN_FILE``` 现已弃用... (2认同)

Mat*_*Pag 18

我已经尝试了很多东西让它在Marshmallow和Lollipop上运行.最后,我最终将保存的图片移动到DCIM文件夹(新的Google Photo应用程序扫描图像只有当它们显然位于此文件夹内时)

public static File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
         .format(System.currentTimeInMillis());
    File storageDir = new File(Environment
         .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/");
    if (!storageDir.exists())
        storageDir.mkdirs();
    File image = File.createTempFile(
            timeStamp,                   /* prefix */
            ".jpeg",                     /* suffix */
            storageDir                   /* directory */
    );
    return image;
}
Run Code Online (Sandbox Code Playgroud)

然后是扫描文件的标准代码,您也可以在Google Developers网站上找到这些代码.

public static void addPicToGallery(Context context, String photoPath) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(photoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}
Run Code Online (Sandbox Code Playgroud)

请记住,此文件夹无法存在于世界上的每个设备中,并且从Marshmallow(API 23)开始,您需要向用户请求WRITE_EXTERNAL_STORAGE的权限.

  • 这是一个也是唯一一个解释得很好的解决方案。没有其他人提到该文件必须在 DCIM 文件夹中。谢谢!!! (3认同)
  • 现在在API 29上已不建议使用getExternalStoragePublicDirectory()。需要使用MediaStore (2认同)

Céd*_*ien 12

根据这个课程,正确的方法是:

Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    )
Run Code Online (Sandbox Code Playgroud)

这将为您提供gallery目录的根路径.

  • ```Environment.getExternalStoragePublicDirectory``` 已被弃用... (2认同)

小智 11

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}
Run Code Online (Sandbox Code Playgroud)


jav*_*tar 5

您可以在相机文件夹中创建一个目录并保存.完成后扫描一下.它会立即在图库中显示您的图像.干杯!!

            String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()+ "/Camera/Your_Directory_Name";
            File myDir = new File(root);
            myDir.mkdirs();
            String fname = "Image-" + image_name + ".png";
            File file = new File(myDir, fname);
            System.out.println(file.getAbsolutePath());
            if (file.exists()) file.delete();
            Log.i("LOAD", root + fname);
            try {
                FileOutputStream out = new FileOutputStream(file);
                finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            MediaScannerConnection.scanFile(context, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

163042 次

最近记录:

6 年,12 月 前