android perfectly realized photo selection image clipping and other code sharing
- 2020-12-18 01:55:08
- OfStack
The version compatibility problem is mainly caused by the different formats of Uri before and after 4.4
1. Take pictures and select pictures
Select a picture
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_REQUEST_CODE);
(2) photos
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
2. Get the value passed by the system
markers
private static int CAMERA_REQUEST_CODE = 1;
private static int GALLERY_REQUEST_CODE = 2;
private static int CROP_REQUEST_CODE = 3;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE) {
if (data == null) {
return;
} else { // Taking pictures
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap bm = extras.getParcelable("data");
Uri uri = saveBitmap(bm);
startImageZoom(uri);
}
}
} else if (requestCode == GALLERY_REQUEST_CODE) {
if (data == null) {// Photo album
return;
}
Uri uri;
uri = data.getData();
Uri fileUri = convertUri(uri);
startImageZoom(fileUri);
} else if (requestCode == CROP_REQUEST_CODE) {
if (data == null) {
return;
}// Cropped picture
Bundle extras = data.getExtras();
if (extras == null) {
return;
}
Bitmap bm = extras.getParcelable("data");
ShowImageView(bm);
}
}
3. After the picture is selected, it is converted to stream according to Url and saved
private Uri convertUri(Uri uri) {
InputStream is = null;
try {
is = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
return saveBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
4. Remember to add permission to save pictures
private Uri saveBitmap(Bitmap bm) {
File tmpDir = new File(Environment.getExternalStorageDirectory()
+ "/xiaoxin");
if (!tmpDir.exists()) {
tmpDir.mkdir();
}
File img = new File(tmpDir.getAbsolutePath() + "love.png");
try {
FileOutputStream fos = new FileOutputStream(img);
bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
fos.flush();
fos.close();
Toast.makeText(MainActivity.this, " A success ", Toast.LENGTH_SHORT).show();
return Uri.fromFile(img);
} catch (FileNotFoundException e) {
Toast.makeText(MainActivity.this, " The loss of � ", Toast.LENGTH_SHORT).show();
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, " The loss of � ", Toast.LENGTH_SHORT).show();
return null;
}
}
Crop the picture
/**
* Cut images
*
* @param uri
*/
private void startImageZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, CROP_REQUEST_CODE);
}
Let's look at an example: first part of the code, the part is extracted from the network, and then used as a tool class
Configuration file: The layout is very simple, 1 ImageButton and 1 Button, click can realize the image selection function, the specific implementation according to the actual effect you use
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cogent.piccut"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".PicCutActivity"
android:screenOrientation="portrait" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
Java code:
package com.cogent.piccut;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
public class PicCutActivity extends Activity implements OnClickListener {
private ImageButton img_btn;
private Button btn;
private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// Taking pictures
private static final int PHOTO_REQUEST_GALLERY = 2;// Select from the album
private static final int PHOTO_REQUEST_CUT = 3;// The results of
// create 1 Three files named with the current time
File tempFile = new File(Environment.getExternalStorageDirectory(),getPhotoFileName());
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
// Initialization control unit
private void init() {
img_btn = (ImageButton) findViewById(R.id.img_btn);
btn = (Button) findViewById(R.id.btn);
// for ImageButton and Button Add a listener event
img_btn.setOnClickListener(this);
btn.setOnClickListener(this);
}
// Click on the event
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.img_btn:
showDialog();
break;
case R.id.btn:
showDialog();
break;
}
}
// Prompt dialog method
private void showDialog() {
new AlertDialog.Builder(this)
.setTitle(" Head set ")
.setPositiveButton(" Taking pictures ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
// Call the camera function of the system
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Specifies the path to store photos after the camera is called to take them
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(tempFile));
startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
}
})
.setNegativeButton(" Photo album ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
}
}).show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case PHOTO_REQUEST_TAKEPHOTO:
startPhotoZoom(Uri.fromFile(tempFile), 150);
break;
case PHOTO_REQUEST_GALLERY:
if (data != null)
startPhotoZoom(data.getData(), 150);
break;
case PHOTO_REQUEST_CUT:
if (data != null)
setPicToView(data);
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startPhotoZoom(Uri uri, int size) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// crop for true It's set on intent Set to display view You can cut
intent.putExtra("crop", "true");
// aspectX aspectY It's the ratio of width to height
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX,outputY It's the width and height of the cropped image
intent.putExtra("outputX", size);
intent.putExtra("outputY", size);
intent.putExtra("return-data", true);
startActivityForResult(intent, PHOTO_REQUEST_CUT);
}
// Displays the cropped image to UI On the interface
private void setPicToView(Intent picdata) {
Bundle bundle = picdata.getExtras();
if (bundle != null) {
Bitmap photo = bundle.getParcelable("data");
Drawable drawable = new BitmapDrawable(photo);
img_btn.setBackgroundDrawable(drawable);
}
}
// Use the current system date to adjust as the name of the photo
private String getPhotoFileName() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
return dateFormat.format(date) + ".jpg";
}
}
Result summary: Androi system with the function of image clipping, development is as long as the call, Intent many practical usage, but too much, need to query or look at the official documentation more at ordinary times, looked at a lot of code simple, but still to be practical to write better, understand more deeply 1.