Created
March 16, 2021 15:31
-
-
Save esabook/f0b2d757272cc039e4b0225c449b00e1 to your computer and use it in GitHub Desktop.
[Android] Pick image from gallery or camera
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package *; | |
import android.Manifest; | |
import android.annotation.SuppressLint; | |
import android.content.Intent; | |
import android.content.pm.PackageManager; | |
import android.graphics.Bitmap; | |
import android.net.Uri; | |
import android.os.Build; | |
import android.os.Bundle; | |
import android.os.Environment; | |
import android.provider.MediaStore; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.ImageButton; | |
import android.widget.Toast; | |
import androidx.annotation.NonNull; | |
import androidx.annotation.Nullable; | |
import androidx.core.app.ActivityCompat; | |
import androidx.core.content.ContextCompat; | |
import androidx.core.content.FileProvider; | |
import com.bumptech.glide.Glide; | |
import com.bumptech.glide.request.target.SimpleTarget; | |
import com.bumptech.glide.request.transition.Transition; | |
import com.google.android.material.bottomsheet.BottomSheetDialogFragment; | |
import java.io.File; | |
import java.io.IOException; | |
/** | |
* example usage: | |
* <p> | |
* mImagePickerDialog = new ImagePickerDialog(); | |
* mImagePickerDialog.setImageSelectedListener(this); | |
* mImagePickerDialog.show(getActivity().getSupportFragmentManager(), null); | |
*/ | |
public class ImagePickerDialog extends BottomSheetDialogFragment implements View.OnClickListener { | |
public static final String TAG = ImagePickerDialog.class.getSimpleName(); | |
public static final int MODE_GALLERY = 6, MODE_CAMERA = 7; | |
public onImageSelectedListener mImageSelectedListener; | |
String filePhotoName = System.currentTimeMillis() + ".png"; | |
File filePhoto; | |
public ImagePickerDialog() { | |
super(); | |
} | |
@SuppressLint("ValidFragment") | |
public ImagePickerDialog(onImageSelectedListener listener) { | |
super(); | |
this.mImageSelectedListener = listener; | |
} | |
@Override | |
public int getTheme() { | |
return R.style.AppTheme_PopupAlertDialog; | |
} | |
public void setImageSelectedListener(onImageSelectedListener mImageSelectedListener) { | |
this.mImageSelectedListener = mImageSelectedListener; | |
} | |
@Override | |
public void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
createPhotoFile(); | |
} | |
@Nullable | |
@Override | |
public View onCreateView(@NonNull LayoutInflater inflater, | |
@Nullable ViewGroup container, | |
@Nullable Bundle savedInstanceState) { | |
View v = inflater.inflate(R.layout.dialog_image_picker, null); | |
initViewBehavior(v); | |
return v; | |
} | |
void initViewBehavior(View v) { | |
ImageButton headerCloseButton = v.findViewById(R.id.header_button); | |
View optionGalley = v.findViewById(R.id.option_gallery); | |
View optionCamera = v.findViewById(R.id.option_camera); | |
headerCloseButton.setOnClickListener(this); | |
optionGalley.setOnClickListener(this); | |
optionCamera.setOnClickListener(this); | |
} | |
private void createPhotoFile() { | |
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { | |
filePhoto = new File( | |
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), | |
filePhotoName); | |
} else { | |
try { | |
filePhoto = File.createTempFile( | |
filePhotoName, | |
null, | |
getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) | |
); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
private Uri getPhotoFileUri() { | |
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { | |
return Uri.fromFile(filePhoto); | |
} else { | |
return FileProvider.getUriForFile( | |
getContext(), | |
BuildConfig.FILE_PROVIDER, | |
filePhoto | |
); | |
} | |
} | |
@Override | |
public void onClick(View v) { | |
switch (v.getId()) { | |
case R.id.header_button: { | |
dismiss(); | |
break; | |
} | |
case R.id.option_gallery: { | |
if (isStoragePermissionGranted()) { | |
choosePhotoFromGallery(); | |
} else { | |
requestAccessPermission(); | |
} | |
break; | |
} | |
case R.id.option_camera: { | |
if (isCameraPermissionGranted() && isStoragePermissionGranted()) { | |
takePhotoFromCamera(); | |
} else { | |
requestAccessPermission(); | |
} | |
break; | |
} | |
} | |
} | |
boolean isStoragePermissionGranted() { | |
return PackageManager.PERMISSION_GRANTED == | |
ContextCompat.checkSelfPermission(getActivity(), | |
Manifest.permission.READ_EXTERNAL_STORAGE); | |
} | |
boolean isCameraPermissionGranted() { | |
return PackageManager.PERMISSION_GRANTED == | |
ContextCompat.checkSelfPermission(getActivity(), | |
Manifest.permission.CAMERA); | |
} | |
void requestAccessPermission() { | |
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), | |
Manifest.permission.READ_EXTERNAL_STORAGE) || !isStoragePermissionGranted()) { | |
toast("Izin eksternal memori diperlukan untuk aplikasi ini."); | |
} | |
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), | |
Manifest.permission.CAMERA) || !isCameraPermissionGranted()) { | |
toast("Izin akses camera diperlukan untuk aplikasi ini."); | |
} | |
ActivityCompat.requestPermissions(getActivity(), new String[]{ | |
Manifest.permission.READ_EXTERNAL_STORAGE, | |
Manifest.permission.CAMERA | |
}, 0); | |
} | |
public void takePhotoFromCamera() { | |
try { | |
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); | |
intent.putExtra(MediaStore.EXTRA_OUTPUT, getPhotoFileUri()); | |
startActivityForResult(intent, MODE_CAMERA); | |
} catch (SecurityException s) { | |
toast("Tidak dapat membuka kamera."); | |
s.printStackTrace(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
public void choosePhotoFromGallery() { | |
try { | |
Intent galleryIntent = new Intent(Intent.ACTION_PICK, | |
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); | |
startActivityForResult(galleryIntent, MODE_GALLERY); | |
} catch (Exception e) { | |
toast("Tidak dapat membuka galeri."); | |
e.printStackTrace(); | |
} | |
} | |
protected void resolveBitmapFromGallery(Intent data) { | |
if (data != null) { | |
Uri contentURI = data.getData(); | |
try { | |
if (contentURI == null) return; | |
Glide.with(getActivity()) | |
.asBitmap() | |
.dontTransform() | |
.load(contentURI) | |
.into(new SimpleTarget<Bitmap>() { | |
@Override | |
public void onResourceReady(@NonNull Bitmap resource, | |
@Nullable Transition<? super Bitmap> transition) { | |
if (mImageSelectedListener != null) | |
mImageSelectedListener.ImagePicked(resource, filePhotoName); | |
} | |
}); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
protected void resolveBitmapFromCameraIntent() { | |
try { | |
Glide.with(getActivity()) | |
.asBitmap() | |
.dontTransform() | |
.load(getPhotoFileUri()) | |
.into(new SimpleTarget<Bitmap>() { | |
@Override | |
public void onResourceReady(@NonNull Bitmap resource, | |
@Nullable Transition<? super Bitmap> transition) { | |
if (mImageSelectedListener != null) | |
mImageSelectedListener.ImagePicked(resource, filePhotoName); | |
} | |
}); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
@Override | |
public void onActivityResult(int requestCode, int resultCode, Intent data) { | |
super.onActivityResult(requestCode, resultCode, data); | |
if (requestCode == MODE_GALLERY) { | |
resolveBitmapFromGallery(data); | |
} else if (requestCode == MODE_CAMERA) { | |
resolveBitmapFromCameraIntent(); | |
} | |
dismissAllowingStateLoss(); | |
} | |
void toast(String msg) { | |
Toast.makeText(getContext(), | |
msg, | |
Toast.LENGTH_LONG) | |
.show(); | |
} | |
public interface onImageSelectedListener { | |
void ImagePicked(Bitmap b, String name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment