将相机图像保存到目录中

时间:2014-09-18 11:05:09

标签: android image directory android-camera

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

我还提到了清单中的权限。

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

         }

1 个答案:

答案 0 :(得分:2)

您需要使用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设备上进行测试以确认其正常工作