【问题标题】:save camera image into directory将相机图像保存到目录中
【发布时间】:2014-11-12 16:40:11
【问题描述】:

我正在开发一个应用程序,在该应用程序中,我必须单击相机中的图像并将其保存到目录中。我能够创建名为 MyPersonalFolder 的目录,并且图像也会进入其中,但是当我正在尝试打开该图像以查看,它没有打开并显示该图像无法打开的消息。这是我的代码。谁能告诉我我在这里犯了什么错误。

我还在 manifest 中提到了权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />





 public class Camera extends Activity{

    private static final String TAG = "Camera";

    private static final int CAMERA_PIC_REQUEST = 1111;
    Button click , share;
    ImageView image;
    String to_send;
    String filename;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);

image = (ImageView)findViewById(R.id.image);

        share = (Button)findViewById(R.id.share);

        click = (Button)findViewById(R.id.click);

        click.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                startActivityForResult(intent, CAMERA_PIC_REQUEST);

            }
        });

        share.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

              BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();

                Bitmap bitmap = bitmapDrawable.getBitmap();

                // Save this bitmap to a file.
                File cache = getApplicationContext().getExternalCacheDir();
                File sharefile = new File(cache, "toshare.png");
                try {
                FileOutputStream out = new FileOutputStream(sharefile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
                } catch (IOException e) {
                }

                // Now send it out to share
                Intent share = new Intent(android.content.Intent.ACTION_SEND);
                share.setType("image/*");
                share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
                try {
                startActivity(Intent.createChooser(share, "Share photo"));
                } catch (Exception e) {
                }
                 /*Intent share = new Intent(Intent.ACTION_SEND);
                 share.setType("text/plain");
                 //String to_send = null;
                share.putExtra(Intent.EXTRA_TEXT, to_send);

                 startActivity(Intent.createChooser(share, "Share using..."));*/

            }
        });
    }
         protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                FileOutputStream outStream = null;
                if (requestCode == CAMERA_PIC_REQUEST) {
                    //2
                    Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
                    image.setImageBitmap(thumbnail);
                    //3
                    share.setVisibility(0);
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                    //4
                    try {
                    File sdCard = Environment.getExternalStorageDirectory();
                    File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
                    dir.mkdirs();   
                    String fileName = String.format("%d.jpg", System.currentTimeMillis());
                    File outFile = new File(dir, fileName);

                    outStream = new FileOutputStream(outFile);
                    //outStream.write(data[0]);
                    outStream.flush();
                    outStream.close();

                    //Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());

                    refreshGallery(outFile);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {


                    /*try {
                        file.createNewFile();
                        FileOutputStream fo = new FileOutputStream(file);
                        //5
                        fo.write(bytes.toByteArray());
                        fo.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();*/
                    }
                }
         }

            private void refreshGallery(File file) {
                Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                mediaScanIntent.setData(Uri.fromFile(file));
                sendBroadcast(mediaScanIntent);
            }   

         }

【问题讨论】:

    标签: android image directory android-camera


    【解决方案1】:

    您需要使用 MediaScanner 通知系统新文件/目录。您可以在创建并保存新文件后尝试这样的操作:

    /**
     * Adds the new photo/video to the device gallery, else it will remain only visible via sd card
     *
     * @param path
     */
    public static void addToGallery(Context context, String path) {
        MediaScanner scanner = new MediaScanner(path, null);
        MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
        scanner.connection = connection;
        connection.connect();
    }
    
    /**
     * Scans the sd card for new videos/images and adds them to the gallery
     */
    private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
        private final String path;
        private final String mimeType;
        MediaScannerConnection connection;
    
        public MediaScanner(String path, String mimeType) {
            this.path = path;
            this.mimeType = mimeType;
        }
    
        @Override
        public void onMediaScannerConnected() {
            connection.scanFile(path, mimeType);
        }
    
        @Override
        public void onScanCompleted(String path, Uri uri) {
            connection.disconnect();
        }
    } 
    

    编辑:

    您还忘记了将字节数组写入输出流中指定的文件,就像您注释掉的代码一样。最后在刷新图库之前尝试此操作:

    outStream = new FileOutputStream(outFile);
    outStream.write(bytes.toByteArray()); //this is the line you had missing
    outStream.flush();
    outStream.close();
    

    另外请注意,使用 Intent.ACTION_MEDIA_SCANNER_SCAN_FILE 刷新图库也可能会在 kitkat 上出现一些安全问题(不记得确切的问题是什么)。因此,请确保您在 kitkat 设备上对其进行测试以确认其正常工作

    【讨论】:

    • 嗨,克里斯,感谢您宝贵的时间。克里斯我已经编辑了我的问题,请你看一下。 :)
    • 很棒的编辑,很高兴看到您不只是盲目地遵循复制粘贴的方法!请查看我的编辑,因为它更适合格式化
    • 非常感谢克里斯,它在 KitKat(4.4.2 和 4.4.4)中也运行良好且正常。 thnx,thnx 很多克里斯。 :)
    • 好东西,很高兴我们能解决这个问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2013-07-29
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多