How to select and crop an image in android? - java

Hey, I am currently working on a live wallpaper and I allow the user to select an image which will go behind my effects.
Currently I have:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra("crop", "true");
startActivityForResult(i, 1);
And slightly under that:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
Log.d("IMAGE SEL", "" + selectedImage);
// TODO Do something with the select image URI
SharedPreferences customSharedPreference = getSharedPreferences("imagePref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
Log.d("HO", "" + selectedImage);
editor.putString("imagePref", getRealPathFromURI(selectedImage));
Log.d("IMAGE SEL", getRealPathFromURI(selectedImage));
editor.commit();
}
}
When my code is ran, Logcat tells me that selectedImage is null. If I comment out the
i.putExtra("crop", "true"):
Logcat does not give me the null pointer exception, and I am able to do what I want with the image. So, what is the problem here? Does any one have any idea how I can fix this? Thanks, for your time.

I have also faced this problem .You can try with this code. Its working fine for me
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
file.createNewFile();
} catch (IOException e) {}
return file;
} else {
return null;
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null) {
File tempFile = getTempFile();
String filePath= Environment.getExternalStorageDirectory()
+"/"+TEMP_PHOTO_FILE;
System.out.println("path "+filePath);
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
_image = (ImageView) findViewById(R.id.image);
_image.setImageBitmap(selectedImage );
if (tempFile.exists()) tempFile.delete();
}
}
}
}

You don't need a Temp file:
protected static final int REQ_CODE_PICK_IMAGE = 1;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("return-data", true);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null) {
Bundle extras = imageReturnedIntent.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
imageR = (ImageView) findViewById(R.id.image);
imageR.setImageBitmap(selectedBitmap);
}
}
}
}

This code good with "beginners" ^^
private Bitmap FixBitmap;
Bitmap thePicBitmap;
String ImagePath = "image_path";
String ImagePath_1;
private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
private static final int REQ_CODE_PICK_IMAGE = 0;
#Override
public void onClick(View view) {
try {
//intent = new Intent();
// intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//intent.setAction(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("scale", true);
photoPickerIntent.putExtra("aspectX", 1);
photoPickerIntent.putExtra("aspectY", 1);
// indicate output X and Y
photoPickerIntent.putExtra("outputX", 150);
photoPickerIntent.putExtra("outputY", 100);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
} catch (Exception e) {
// Toast.makeText(getApplicationContext(), R.string.imageException, Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
Toast toast = Toast.makeText(Upload_image_text.this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (isSDCARDMounted()) {
File f = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
}
return f;
} else {
return null;
}
}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
});
=======================
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null){
// File tempFile = getTempFile();
ImagePath_1 = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
System.out.println("path "+ImagePath_1);
FixBitmap = BitmapFactory.decodeFile(ImagePath_1);
ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}
}
}
===============================
#Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
//options.outWidth = 50;
//options.outHeight = 50;
FixBitmap = BitmapFactory.decodeFile(ImagePath_1, options);
//FixBitmap = BitmapFactory.decodeResource(getResources(), R.id.imageView);
byteArrayOutputStream = new ByteArrayOutputStream();
FixBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); //compress to 50% of original image quality
byteArray = byteArrayOutputStream.toByteArray();
ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

Related

Uploading and retrieving image android studio Parse sever

I'm trying to pick multiple images from users gallery and upload (parse server) this images to parse object then retrieve it and set it in an image view
and also i need to pick one image from gallery and save to the users profile
what i have already tried:
//Before OnCreate
String da = "13412412412412414124ASDASDASDASDAD";
////After OnCreate
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final Uri imageUri = data.getData();
final InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
String encodedImage = encodeImage(selectedImage);
da=encodedImage;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private String encodeImage(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
private void ChooseImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
}
private void CreateThing() {
ParseObject thing = new ParseObject("Things");
thing.put("Image",da);
thing.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e==null)
Toast.makeText(class.this, "Done", Toast.LENGTH_SHORT).show();
else
Toast.makeText(class.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

Bitmap is null while capturing image from camera

My code is working perfectly fine in API level <= 19 but in greater version I am getting bitmap null.
public void SelectImage() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.add_image);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(mainActivity.getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CAMERA);
}
} else if (items[i].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, SELECT_FILE);
} else if (items[i].equals("Cancel")) {
dialog.dismiss();
}
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(data, mainActivity);
etAddress1.setText(place.getAddress());
}
} else if (resultCode == Activity.RESULT_OK && data != null) {
Glide.with(this).load(data.getData()).into(ivprofile);
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mainActivity.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] b = baos.toByteArray();
base64img = Base64.encodeToString(b, Base64.NO_WRAP);
}
}
Here my bm is null why this happening am i using the older code version or is there anything else.. Thanks in advance.
Actually, there is a library which works with every phone and every android version. If you need to solve you problem here is an answer. EasyImage did the job!
do not forget to handle permissions api 23 and up !

Take pictures and saving to SD card

I am trying to develop an app where you can take pictures and then display them on screen or upload a picture from your SD card and display on screen. Currently I am app to upload and display it on screen however when i select the option to take a photo I am able to take the photo and click save, however, the photo will not display on the screen nor will it save to the SD card. Please help!
public class UploadActivity extends Fragment {
private Button bt_browse;
private ImageView iv_photo;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String uploadImagePath = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.upload,
container, false);
bt_browse = (Button) rootView.findViewById(R.id.button1);
iv_photo = (ImageView) rootView.findViewById(R.id.iv_photo);
bt_browse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectImage();
}
});
return rootView;
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv_photo.setImageBitmap(bm);
uploadImagePath = f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
iv_photo.setImageBitmap(bm);
uploadImagePath = tempPath;
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
I have also added the following code to the Manifest file
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
i was handled this Scenario with this methods as:
private void getImageFromCamera() {
Log.i("GalaNotes", "From CAMERA Setting Capture TRUE");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
private void getImageFromGallery() {
Log.i("GalaNotes", "From Gallery Setting Capture TRUE");
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_FROM_FILE);
}
In the onActivityResult() method you can print the Uri or Path where it was stored as follows :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_CAMERA:
try {
log.i("Stored location of File",getRealPathFromURI(mImageCaptureUri));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
Log.d("PHOTO", "" + mImageCaptureUri.toString()); // UPLOAD FEEDS
// RESPONSE
// doCrop();
Intent i = new Intent(activity, CropActivity.class);
try {
i.putExtra("imgSdcardPath", getRealPathFromURI(mImageCaptureUri));// mImageCaptureUri.toString());
startActivityForResult(i, 212);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}}
If You have any Query then givefeedback on my Post.
Try the standart way to get the photo from onActivityResult:
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
// Global Declaration
Intent intent;
String imageFileName,videoFileName;
Uri uri;
private void clickPhotoFromCamera() {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imageFileName = "JPEG_" + timeStamp + ".jpg";
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), imageFileName);
uri = Uri.fromFile(imageStorageDir);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 1);
}
private void captureVideoFromCamera() {
intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
videoFileName = "VID_" + timeStamp + ".mp4";
File videoStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), videoFileName);
uri = Uri.fromFile(videoStorageDir);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 2);
}
private void uploadMediaFromGallery() {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(intent, 3);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
imagePath = uri.getPath();
// Do whatever you want with image path...
} else if (requestCode == 2) {
videoPath = uri.getPath();
// Do whatever you want with Video path...
} else {
uri = data.getData();
mediaPath = getPath(getApplicationContext(), uri);
}
}
}
// For get Image or video from path...
File mediaFile = new File(mediaPath);
Bitmap bitmap;
if (mediaFile.exists()) {
if (isImage(mediaPath)) {
Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth());
Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true);
int rotate = 0;
try {
exif = new ExifInterface(mediaFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
rotate = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
Bitmap rotateBitmap = Bitmap.createBitmap(scale, 0, 0, scale.getWidth(), scale.getHeight(), matrix, true);
displayImage.setImageBitmap(rotateBitmap);
} else {
bitmap = ThumbnailUtils.createVideoThumbnail(mediaPath, Thumbnails.MICRO_KIND);
displayImage.setImageBitmap(bitmap);
}
}
public static boolean isImage(String str) {
boolean temp = false;
String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" };
for (int i = 0; i < arr.length; i++) {
temp = str.endsWith(arr[i]);
if (temp) {
break;
}
}
return temp;
}

UnsupportedOperationException Error while opening camera android

I am doing an Android application which need to open camera and display picture on screen and take that picture absolute path.
But I always get "UnsupportedOperationException: Unknown URI: content://media/external/images/media" error when I click on camera.
My code:
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "ircms");
imgUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); // Here getting error
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intentPicture, 1);
onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
try {
String photoPath = getRealPathFromURI(this, imgUri);
o2.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, o2);
}
}
}
Please Help...
try this
What Do you Need
In Manafiest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In your activity
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getTempFile(Context context){
//it will return /sdcard/image.tmp
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case TAKE_PHOTO_CODE:
final File file = getTempFile(this);
try {
Bitmap captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
// do whatever you want with the bitmap (Resize, Rename, Add To Gallery, etc)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
Use this code to get file path of the image in onActivityResult
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}

Android Saved images are low quality

I'm taking pictures through the following code and saving to SD card, but the pictures that it produces are such low quality and really bitty even with 100% quality. Maybe bitmap.compress isn't the right way to go (or bitmap at all?!)
Heres my code:
public class TakePhoto extends Activity {
ImageView iv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_photo);
iv = (ImageView) findViewById(R.id.imageView1);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = (Bitmap) data.getExtras().get("data");
Random generator = new Random();
String randFileName = String.valueOf (generator.nextInt(965) + 32);
String both = "/mnt/extSdCard/DirectEnquiries/"+ randFileName + ".jpg";
File imageFile = new File(both);
writeBitmapToMemory(imageFile, bm);
iv.setImageBitmap(bm);
}
public void writeBitmapToMemory(File file, Bitmap bitmap) {
FileOutputStream fos;
try {
Log.e("Tom", "Starting take stream");
fos = new FileOutputStream(file);
Log.e("Tom", "Got stream");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.e("Tom", "Saved Image");
fos.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Please call the below function to capture image from camera.
private final static String FOLDER_NAME = "YourAppName/Image/";
private Uri selectedImageUri = null;
public void startCamera()
{
File photo = null;
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
photo = new File(android.os.Environment.getExternalStorageDirectory(), FOLDER_NAME+File.separator+timeStamp+".png");
}
else
{
photo = new File(getCacheDir(), FOLDER_NAME+File.separator+timeStamp+".png");
}
if (photo != null)
{
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
selectedImageUri = Uri.fromFile(photo);
startActivityForResult(intent, CAPTURE_IMAGE_CALLBACK);
}
}
You can get image Uri in selectedImageUri variable . (Image is stored in Sdcard)
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case CAPTURE_IMAGE_CALLBACK:
break;
}
}
Have you tried setting quality in the intent?
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);

Categories