将图像从图像视图保存到内部/外部设备存储

时间:2017-01-31 08:06:49

标签: android image android-studio android-fragments camera

我是原生android开发的新手。我正在处理android studio并初始化tabbed activity。第一个标签用于map第二个标签,用于camera。对于相机,我使用image viewbutton将打开相机。现在,我能够看到image view中拍摄的当前图像,但我想将其保存到我的internal/external设备存储中。为此,我搜索了许多下面的文章。

  1. Link 1
  2. Link 2
  3. Link 3
  4. 但找不到一个好的解决方案。此外,我正在使用片段来做到这一点。 以下是我的清单。

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.accurat.faisal">
    
    <permission android:name="com.example.accurat.faisal.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    
    <uses-permission android:name="com.example.accurat.faisal.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"
        />
    
    
    <application
         android:name="android.support.multidex.MultiDexApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="MY_KEY"
            />
    
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    

    以下是我的相机布局

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.accurat.faisal.MainActivity$PlaceholderFragment">
    
    
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@android:drawable/ic_menu_camera"
        android:id="@+id/imageView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_above="@+id/getpicture" />
    
    <Button
        android:id="@+id/getpicture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take Picture"
        android:layout_marginBottom="52dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" /></RelativeLayout>
    

    以下是我拍摄图像的java代码

    public class Camera extends Fragment {
    
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
    public static final int REQUEST_CAMERA = 1;
    Button button;
    ImageView imageView;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
      final View rootView = inflater.inflate(R.layout.camera, container, false);
    
        button = (Button)rootView.findViewById(R.id.getpicture);
        imageView = (ImageView)rootView.findViewById(R.id.imageView);
    
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Check permission for CAMERA
                if (ActivityCompat.checkSelfPermission(getActivity(), CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
    
                    // Check Permissions Now
                    // Callback onRequestPermissionsResult interceptado na Activity MainActivity
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{CAMERA},
                            Camera.REQUEST_CAMERA);
    
                }
                else {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );
    
                }
    
    
            }
        });
    
    
    
        return rootView;
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            if (resultCode == Activity.RESULT_OK)
            {
                Bitmap bmp = (Bitmap)data.getExtras().get("data");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
    
                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
    
                // convert byte array to Bitmap
    
                Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                        byteArray.length);
    
                imageView.setImageBitmap(bitmap);
    
            }
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Toast.makeText(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                } else {
    
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
                }
                return;
            }
    
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }}
    

    贝娄是我的包括

    import static android.Manifest.permission.CAMERA;
    import static android.Manifest.permission.RECORD_AUDIO;
    import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
    import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
    

    我研究过如何保存图像但却无法理解。我肯定错过了一些我不知道的事情

    任何帮助都将受到高度赞赏

3 个答案:

答案 0 :(得分:4)

onActivityResult()

中试用此代码
if(isStoragePermissionGranted()){
    SaveImage(bitmap)
    }

用于保存图像:

 private void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
}

使用此方法进行权限检查:

    public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

获得结果:

 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CAMERA: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                Toast.makeText(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        case 2: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                SaveImage(bitmap);
            } else {
                Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
 }

答案 1 :(得分:0)

首先,你的onActivityResult搞砸了,你不需要转换Bitmap - &gt;流 - &gt;位图使用来自Intent的bitap来保存图像。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        if (resultCode == Activity.RESULT_OK)
        {
            Bitmap bmp = (Bitmap)data.getExtras().get("data");
            imageView.setImageBitmap(bmp);

            // here try to inovke saveImageMethod
        }
    }
}

public void saveImage(Bitmap bmp, String filename)
{
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(filename);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

但请记住要求外部存储权限。如果您希望共享此文件,则必须使用FileProvider api。有关详细信息,请查看 https://developer.android.com/training/basics/data-storage/files.html

答案 2 :(得分:0)

您可以使用以下代码

将图像保存在内部存储空间中
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
    if (resultCode == Activity.RESULT_OK)
    {
        Bitmap bmp = (Bitmap)data.getExtras().get("data");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        //saving image into internal storage

        File myfile = new File(Environment.getExternalStorageDirectory(),"yourfilename.jpg");

        FileOutputStream fo;
        try {
            myfile.createNewFile();
            fo = new FileOutputStream(myfile);
            fo.write(byteArray);
            fo.flush();
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // convert byte array to Bitmap

        Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                byteArray.length);

        imageView.setImageBitmap(bitmap);

    }
  }
}