天道酬勤,学无止境

save the image to the gallery in android

How can i save the image that the camera take into the gallery? i have this code but doesn't save the image

private File createImageFile() throws IOException {
// Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );

// Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

and almost use thise one

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);
    }

but doesn't have a positive result, in my manifest i use this permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>
标签

评论

From android version M and above, Runtime permission is required for any dangerous permission - https://developer.android.com/guide/topics/permissions/requesting.html#normal-dangerous

public void checkPermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (!(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (!(grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
        Log.d(TAG, "Storage Permission not granted");   
    } else {
        // Permission granted - resume
    }
}

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 如何在Android Gallery中保存图像(How to save image in android gallery)
    问题 我尝试将图像保存到WathsappIMG中,但是当我转到Android图像画廊时,我看不到图像,并且可以从ES File Explorer中看到该图像到目录中 OutputStream output; // Find the SD Card path File filepath = Environment.getExternalStorageDirectory(); // Create a new folder in SD Card File dir = new File(filepath.getAbsolutePath() + "/WhatSappIMG/"); dir.mkdirs(); // Retrieve the image from the res folder BitmapDrawable drawable = (BitmapDrawable) principal.getDrawable(); Bitmap bitmap1 = drawable.getBitmap(); // Create a name for the saved image File file = new File(dir, "Wallpaper.jpg" ); try { output = new FileOutputStream(file); // Compress into png
  • android-将图像保存到图库(android - save image into gallery)
    问题 我有一个带有图片库的应用,我希望用户可以将其保存到自己的库中。 我创建了一个带有单个语音“保存”的选项菜单,但允许的问题是...如何将图像保存到图库中? 这是我的代码: @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
  • 如何将我的imageView图像保存到Gallery中(Android开发)(How do I save my imageView image into Gallery (Android Development))
    问题 我试图创建一个onClick事件,以通过单击一个按钮将imageview保存到手机图库中,这是我的代码。 它不会保存到图库中,有人可以帮助我找出原因吗? sharebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View b) { // TODO Auto-generated method stub //attempt to save the image b = findViewById(R.id.imageView); b.setDrawingCacheEnabled(true); Bitmap bitmap = b.getDrawingCache(); //File file = new File("/DCIM/Camera/image.jpg"); File root = Environment.getExternalStorageDirectory(); File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg"); try { cachePath.createNewFile(); FileOutputStream ostream = new
  • 将图像保存在画廊 android 中(save image in gallery android)
    问题 我正在使用此代码来保存图像: URL url = null; try { url = new URL("image"); } catch (MalformedURLException e1) { e1.printStackTrace(); } Bitmap bmp = null; try { bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException e1) { e1.printStackTrace(); } OutputStream output; File filepath = Environment.getExternalStorageDirectory(); File dir = new File(filepath.getAbsolutePath() + "/folder name/"); dir.mkdirs(); File file = new File(dir, image + ".png"); Toast.makeText(HomeActivity.this, "Image Saved to SD Card", Toast.LENGTH_SHORT).show(); try { output = new
  • 将 ImageView 保存到 Android 模拟器库(Save ImageView to Android Emulator Gallery)
    问题 我想将图像保存到 Android Gallery,这是我当前的代码: image.setDrawingCacheEnabled(true); image.buildDrawingCache(true); Bitmap b = image.getDrawingCache(); if(!new File("/"+Environment.DIRECTORY_PICTURES).exists()) Log.e("Error","/"+Environment.DIRECTORY_PICTURES+" Dont exist"); File file = new File(Environment.DIRECTORY_PICTURES+"/myImage.jpg"); file.createNewFile(); FileOutputStream ostream = new FileOutputStream(file); b.compress(CompressFormat.JPEG, 80, ostream); image.setDrawingCacheEnabled(false); ostream.close(); Toast.makeText(Ads.this, "Offer saved", 1).show(); 它总是返回相同的错误: Error: /Pictures Dont
  • Android-为什么我保存的图像没有出现在手机的默认图片库中?(Android - Why my saved image is not appearing in the default gallery of my phone?)
    问题 我正在尝试将应用程序中的图像保存到手机的默认图片库中。 如果我的手机上装有SD卡,则下面的代码可以完美地工作。 所保存的图像将出现在手机的图库中,并且与预期的一样: private Uri saveMediaEntry(File f, String title, String description, int orientation, Location loc) { ContentValues v = new ContentValues(); v.put(Images.Media.TITLE, title); v.put(Images.Media.DISPLAY_NAME, title); v.put(Images.Media.DESCRIPTION, description); v.put(Images.Media.ORIENTATION, orientation); String nameFile = f.getName(); File parent = f.getParentFile() ; String path = parent.toString().toLowerCase() ; String nameParent = parent.getName().toLowerCase() ; v.put(Images.ImageColumns.BUCKET_ID
  • 如何从android画廊隐藏图像(how to hide images from android gallery)
    问题 我当前项目的一部分是从URL下载图像,然后保存到SDCard。 但是问题是sdcard中所有保存的图像都显示在android gallery页面中。 我想要的是“我不希望所有已保存的图像都在android画廊中。 ” 回答1 添加“ .nomedia”文件。 不工作? 尝试第二个选项。 将文件保存到以“。”开头的文件夹,例如/sdcard/.myimages/ 回答2 您可以使用以下代码创建.nomedia文件: String NOMEDIA=".nomedia"; File Folder = new File(Environment.getExternalStorageDirectory() + "/mydir"); if(Folder.mkdir()) { nomediaFile = new File(Environment.getExternalStorageDirectory() + "/mydir/"+ NOMEDIA); if(!nomediaFile.exists()){ nomediaFile.createNewFile(); } } 回答3 我找到了一种简单的方法(我认为是这样)。 在“ Android”文件夹(其中存在data和obb文件夹)中创建一个文件夹,然后将媒体(图片,视频等)放入您创建的文件夹中。 Gallery应用程序会忽略该“ Android
  • Android - Why my saved image is not appearing in the default gallery of my phone?
    I am trying to save an image from my application to the default gallery of my phone. The code below works perfectly if I have a SD card on the phone. The image saved appears in the phone's gallery and everything, as expected: private Uri saveMediaEntry(File f, String title, String description, int orientation, Location loc) { ContentValues v = new ContentValues(); v.put(Images.Media.TITLE, title); v.put(Images.Media.DISPLAY_NAME, title); v.put(Images.Media.DESCRIPTION, description); v.put(Images.Media.ORIENTATION, orientation); String nameFile = f.getName(); File parent = f.getParentFile()
  • 在 Android 4.3 中将位图保存到磁盘/图库(Saving a bitmap to disk/gallery in Android 4.3)
    问题 我一直在使用系统保存截图的方式将我的位图保存到磁盘和图库中。 这适用于 Android 4.2 及之前版本,但不适用于 Android 4.3。 相关代码: Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); OutputStream out = resolver.openOutputStream(uri); 完整代码在这里。 然而,在 4.3(新的 Nexus 7)中,我在第二行得到一个 FileNotFoundException。 我在网站上看不到 4.3 中与此相关的任何更改。 那么将图像保存到磁盘和图库的正确方法是什么? 验证: 存储是用这种方法挂载的 imageUri 不为空(通常类似于“content://media/external/images/media/2034”) 清单具有权限 android.permission.WRITE_EXTERNAL_STORAGE 回答1 这是我将bitmaps保存到Gallery 的方式: Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri; //instantiate Uri
  • save image in gallery android
    I am using this code to save the image: URL url = null; try { url = new URL("image"); } catch (MalformedURLException e1) { e1.printStackTrace(); } Bitmap bmp = null; try { bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException e1) { e1.printStackTrace(); } OutputStream output; File filepath = Environment.getExternalStorageDirectory(); File dir = new File(filepath.getAbsolutePath() + "/folder name/"); dir.mkdirs(); File file = new File(dir, image + ".png"); Toast.makeText(HomeActivity.this, "Image Saved to SD Card", Toast.LENGTH_SHORT).show(); try { output
  • Image, saved to sdcard, doesn't appear in Android's Gallery app
    I save an image to the sdcard and it doesn't appear in the Gallery application until I pull off the sdcard and return it back. Do you have any idea why is it so? Seems like the Gallery application has some cache that isn't updated on file save... Actually, I also want to open the just-saved image in Gallery application and have no success with that this is my question about this issue.
  • How to save image in android gallery
    I try to save the image into WathsappIMG but when I go to image gallery android I don't see the image and the image there into the directory can be seen from ES File Explorer OutputStream output; // Find the SD Card path File filepath = Environment.getExternalStorageDirectory(); // Create a new folder in SD Card File dir = new File(filepath.getAbsolutePath() + "/WhatSappIMG/"); dir.mkdirs(); // Retrieve the image from the res folder BitmapDrawable drawable = (BitmapDrawable) principal.getDrawable(); Bitmap bitmap1 = drawable.getBitmap(); // Create a name for the saved image File file = new
  • How to create an app image folder to show in Android gallery
    I have an app where the user creates an image and then I want to save it so it's visible form the default gallery application. Now I don't want the pictures to be saved in the same folder as the pictures taken from the camera, I want them to be saved in a folder dedicated to the app, just like images from apps like whatsapp or facebook. I've tried saving them in this two locations: File imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+ File.separator + appDirectoryName + File.separator); and here File imagePath = new File(Environment
  • Save ImageView to Android Emulator Gallery
    I'd like to Save an Image to the Android Gallery, here's my current code: image.setDrawingCacheEnabled(true); image.buildDrawingCache(true); Bitmap b = image.getDrawingCache(); if(!new File("/"+Environment.DIRECTORY_PICTURES).exists()) Log.e("Error","/"+Environment.DIRECTORY_PICTURES+" Dont exist"); File file = new File(Environment.DIRECTORY_PICTURES+"/myImage.jpg"); file.createNewFile(); FileOutputStream ostream = new FileOutputStream(file); b.compress(CompressFormat.JPEG, 80, ostream); image.setDrawingCacheEnabled(false); ostream.close(); Toast.makeText(Ads.this, "Offer saved", 1).show(); It
  • 将图像从ImageView保存到设备库(Save image from ImageView to device gallery)
    问题 我正在尝试将图像从ImageView保存到设备库。 我尝试了这段代码 代码编辑: URL url = new URL(getIntent().getStringExtra("imageURL")); File f = new File(url.getPath()); addImageToGallery(f.getPath(), this); public static void addImageToGallery(final String filePath, final Context context) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.MediaColumns.DATA, filePath); context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); }
  • Share Image Intent with custom Save To Gallery option
    I am using Android's default share intent to share an image to other apps. But I would like to add an option like Save to Gallery which saves that Image directly to Gallery in media or images or my app's folder. Currently I am using the simple code to share image: Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); shareIntent.setType("image/jpeg"); startActivity(Intent.createChooser(shareIntent, "Share to")); When I tried WhatsApp's share button from profile picture, there is an option of "Save To Gallery
  • android - save image into gallery
    i have an app with a gallery of images and i want that the user can save it into his own gallery. I've created an option menu with a single voice "save" to allow that but the problem is...how can i save the image into the gallery? this is my code: @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 {
  • how to paint on an image and save the image to phone gallery in android
    ** my intent is to save the painted image along with my background view to gallery** // public boolean onTouch(View view, MotionEvent event) { // draw the new Points to our internal canvas / bitmap System.out.println("onTouch(View vc) { IS CALLING11111111111"); if (event.getAction() == MotionEvent.ACTION_DOWN) { paint.setColor(Color.RED); path = new Path(); path.moveTo(event.getX(), event.getY()); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { int historySize = event.getHistorySize(); for (int i = 0; i < historySize; i++) { path.lineTo(event.getHistoricalX(i), event.getHistoricalY
  • 在 Xamarin Forms 中将图像从图像框中保存到图库(Save image from an image box to gallery in Xamarin Forms)
    问题 有没有办法将图像控件中的图片保存到 Xamarin Forms 中的 Android 库? 感谢所有帮助。 var image = new Image(); image.Source = "test.png"; 截屏 回答1 您可以使用 Media Plugin,它可以解决您的问题。 https://github.com/jamesmontemagno/MediaPlugin 您可以访问上面的链接。 takePhoto.Clicked += async (sender, args) => { await CrossMedia.Current.Initialize(); if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { DisplayAlert("No Camera", ":( No camera available.", "OK"); return; } var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { Directory = "Sample", Name = "test.jpg" })
  • 如何创建要在 Android 库中显示的应用程序图像文件夹(How to create an app image folder to show in Android gallery)
    问题 我有一个应用程序,用户可以在其中创建一个图像,然后我想保存它,这样它就可以从默认的图库应用程序中看到。 现在我不希望图片与从相机拍摄的图片保存在同一文件夹中,我希望它们保存在专用于应用程序的文件夹中,就像来自 whatsapp 或 facebook 等应用程序的图像一样。 我试过将它们保存在这两个位置: File imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+ File.separator + appDirectoryName + File.separator); 和这里 File imagePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ File.separator + appDirectoryName + File.separator); 如果我浏览手机,我会看到我成功保存了图像,但它们没有显示在图库应用程序中。 很明显我错过了一些东西,但我不知道它是什么。 也许向文件或文件夹添加某种元数据,以便画廊识别它们? 回答1 好吧,我最终找到了答案。 结果是我怀疑的。