I've managed to programmatically take a photo from the camera, then display it on an imageview, and then after pressing a button, saving it on the Gallery.
It works, but the problem is that the saved photo are low resolution.. WHY?!
I took the photo with this code:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Then I save the photo on a var using :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
}
}
and then after displaying it on an imageview, I save it on the gallery with this function:
public void SavePicToGallery(Bitmap picToSave, File savePath){
String JPEG_FILE_PREFIX= "PIC";
String JPEG_FILE_SUFFIX= ".JPG";
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File filePath = null;
try {
filePath = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, savePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picToSave.compress(CompressFormat.JPEG, 100, out);
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Add the pic to Android Gallery
String mCurrentPhotoPath = filePath.getAbsolutePath();
MediaScannerConnection.scanFile(this,
new String[] { mCurrentPhotoPath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
}
I really can't figure out why it lose so much quality while saved..
Any help please ? Thanks..
The photo you are displaying in the ImageView is a thumbnail :
data.getExtras().get("data");
Are you calling the method :
public void SavePicToGallery(Bitmap picToSave, File savePath)
with the thumbnail ?
Here you have all the steps describe to do what you want :
http://developer.android.com/training/camera/photobasics.html
data.getExtras().get("data") only get thumbnail.
To do it properly, you have to declare global uri variable
Uri imageCapturedUri ;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imageCaptureUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
// mImageCaptureUri is your Uri
}
}
Related
I used below codes for taking image from camera and put it in Image View (imgViewAds).
private void BtnPhoto_Click(object sender, EventArgs e)
{
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.SetVmPolicy(builder.Build());
Intent cameraIntent = new Intent(Android.Provider.MediaStore.ActionImageCapture);
var activities = PackageManager.QueryIntentActivities(cameraIntent, 0);
if (activities.Count > 0)
{
addAds.ImageName = Guid.NewGuid().ToString() + ".jpg";
Java.IO.File imageFile = new Java.IO.File(AdsAdapter.ImagePath(addAds.ImageName));
Android.Net.Uri imageUri = Android.Net.Uri.FromFile(imageFile);
cameraIntent.PutExtra(MediaStore.ExtraSizeLimit, 1024*10);
cameraIntent.PutExtra(MediaStore.ExtraOutput, imageUri);
StartActivityForResult(cameraIntent, 0);
}
else
{
Toast.MakeText(this, "Not Camera", ToastLength.Long).Show();
}
}
And here is OnActivityResult the the camare send result here.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (resultCode == Result.Ok && (data != null))
{
Bundle extras = data.Extras;
Bitmap imageBitmap = (Bitmap)extras.Get("data");
imgViewAds.SetImageBitmap(imageBitmap);
MemoryStream stream = new MemoryStream();
imageBitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
addAds.AdsImage = stream.ToArray();
}
base.OnActivityResult(requestCode, resultCode, data);
}
but the data that sending to OnActivityResult is null and Image did not come to Image View.
When you pass EXTRA_OUTPUT with a URI to write to, the camera intent will be null and the picture is in the URI that you passed in.
so you could simply remove these two lines:
Android.Net.Uri imageUri = Android.Net.Uri.FromFile(imageFile);
cameraIntent.PutExtra(MediaStore.ExtraOutput, imageUri);
note that in this way you get the thumbnail of the image. so if you want the whole image you could use something like this (I haven't tested the code, but you could get the idea):
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
addAds.ImageName = Guid.NewGuid().ToString() + ".jpg";
Java.IO.File imageFile = new Java.IO.File(AdsAdapter.ImagePath(addAds.ImageName));
Uri uri = Uri.fromFile(file);
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
bitmap = cropAndScale(bitmap, 300); // if you mind scaling
profileImageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am a very young self taught developer and I'm working on my first major project, which requires to start a camera intent once pressed, save the image that the user took and display it in a custom dialog.
I got it to work, but i stored the returned bitmap in onactivityresult so the picture is compressed and that destroys the functionality of the app.
HERE IS THE CODE THAT DOES WORK:
start intent:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
Recieve Intent and send data to dialog:
Bundle bundle = data.getExtras();
File file = new File(getCacheDir() + "/app"
+ System.currentTimeMillis() + ".jpg");
Bitmap bitmap = (Bitmap) bundle.get("data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100 /* ignored for PNG */,
bos);
byte[] bitmapdata = bos.toByteArray();
// write the bytes in file
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos = new FileOutputStream(file);
fos.write(bitmapdata);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mdialog.setPic(file.getAbsolutePath());
Display the picture in the custom dialog:
public void setPic(final String mURi) {
this.mURI = mURi;
if (mURI != null) {
hwPic.postDelayed(new Runnable() {
#Override
public void run() {
Drawable d = Drawable.createFromPath(mURI);
hwPic.setImageDrawable(d);;
hwPic.setVisibility(View.VISIBLE);
}
}, 1000);
}
}
This works fine but since the picture is compressed any reasonably sized font in the picture is blury and illegible.
HERE IS THE CODE THAT DOES NOT WORK:
Initialize Variable:
private String MURID;
Start intent:
File file = new File(getCacheDir() + "/app"
+ System.currentTimeMillis() + ".jpg");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MURID=file.getAbsolutePath();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT , Uri.parse(MURID));
startActivityForResult(intent, 1);
recieve intent and send to mydialog:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {// camera intent for the dialog picture
if (resultCode == RESULT_OK) {
mdialog.setPic(MURID);
}
}
}
setpic remains the same(in the dialog):
public void setPic(final String mURi) {
this.mURI = mURi;
if (mURI != null) {
hwPic.postDelayed(new Runnable() {
#Override
public void run() {
Drawable d = Drawable.createFromPath(mURI);
hwPic.setImageDrawable(d);;
hwPic.setVisibility(View.VISIBLE);
}
}, 1000);
}
}
Im not getting any response from it and logcat didnt give me any errors either, what seems to be the problem? any help would be greatly apprecieated.
BTW: i want this to work with phones without sdcards as well.
Third-party camera apps cannot write to your getCacheDir(), and some may get confused if you point to an existing file. Use external storage instead:
package com.commonsware.android.camcon;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
public class CameraContentDemoActivity extends Activity {
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
finish();
}
}
}
}
(from this sample project in this book)
BTW: i want this to work with phones without sdcards as well.
External storage is not removable storage.
I have code to show capture image from camera device like this
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String file_name = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
File file = new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + file_name + ".jpg");
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
intent.putExtra("mImageCaptureUri", mImageCaptureUri);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
and set image bitmap from path , it works when I capture image from portrait view camera device , but when I capture image from landscape view camera its getting error , I think its because my activity to retrieve image is portrait . So can u give me advice in order to I can capture image from portrait or landscape view camera?? thanks
try this
at first start intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and then activity for result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if(data!=null && resultCode == RESULT_OK)
{
bitMapForProfilePic = (Bitmap) data.getExtras().get("data");
bitMapForProfilePic =Bitmap.createScaledBitmap(bitMapForProfilePic, getWindowManager().getDefaultDisplay().getWidth()/5, getWindowManager().getDefaultDisplay().getHeight()/4, true);
registration_profilePicID.setImageBitmap(bitMapForProfilePic); bitMapForProfilePic=null;
}
}
}
if u want to store the bitmap
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "profilepicture.PNG");
try {
outStream = new FileOutputStream(file);
bitMapForProfilePic.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
then set the image
view.setImageBitmap(BitmapFactory.decodeFile("/sdcard/profilepicture.PNG"));
if u have any doubts let me know...
I've faced the similar problem in one of my apps, I've fixed it in the following way:
First save your instance state:
#Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString(IMAGE_FILE_PATH, imageFilePath); }
And then restore it:
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
ImageFilePath = state.getString(IMAGE_FILE_PATH); }
That works for me, but variable ImageFilePath should be global for your Activity so maybe there is more graceful way to achieve this
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using Camera and storing captured result in SDCard in android
I want to get picture from camera app, save it on SD and set imageView.
I made a code below. saving and imageView sometimes works. but sometimes the picture is saved on SD and imageView doesn't work.
When imageView doesn't work, it seems that mOutUri become null in onActivityResult.
I have tried to save a mOutUri on SharedPreferences in clkbutton. I can see the uri in onActivityResult but imageView doesn't work. at this time, mOutUri is also null.
public void clkbutton(View v){
Intent intent = new Intent();
// open camera app
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// save data in SD card
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String newPicFile = df.format(date) + ".jpg";
mNewPicFile = newPicFile;
String outPath = "/sdcard/" + newPicFile;
File outFile = new File(outPath);
mOutUri = Uri.fromFile(outFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutUri);
startActivityForResult(intent, REQUEST_CAPTURE_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageURI(mOutUri);
}
It's so weird that it sometimes errors and sometimes works.
In onActivityResult before you setImageUri you should check if file exists. You can lose mOutUri content when app changes orientation, and it happend sometime when you open camera. You should implement in activity onSaveInstanceState where you store into preferences your uri and onRestoreInstanceState where you restore your uri.
try the following code:
static Uri capturedImageUri=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(), (cal.getTimeInMillis()+".jpg"));
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
capturedImageUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(i, CAMERA_RESULT);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
//Bitmap photo = (Bitmap) data.getExtras().get("data");
//imageView.setImageBitmap(photo);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap( getApplicationContext().getContentResolver(), capturedImageUri);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and also dont forget to add some permissions in android manifets file like:
`note: add permission WRITE_EXTERNAL_STORAGE in manifest file.`
in my camera intent:
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
this part gives me a null pointer exception.
can anyone explain why and what need to be changed??
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, TAKE_PICTURE);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
Try the following,
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
WebView webview;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//this is the url that where you are saved the image
}
}