Storing image taken from camera - android

I can take a picture via the following intent
cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Then in the onActivityResult method I set the image taken to an ImageView and attempt to store the image to the SD card with the following function
private void savePic(Bitmap bmp) {
if(!isSDOK || !isSDWritable)
return;
String name = "TESTA";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path,name+".jpg");
path.mkdirs();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bitmapdata);
try{
InputStream is = bis;
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read();
os.write(data);
is.close();
os.close();
}catch(Exception e){Log.e("IMAGE CONVERT ERR", e.toString());}
return;
}
When I check the PICTURES folder i see the file but the image is blank and always 12kb in size. Can't I use my above method to save the image from a bitmap file?

Yes as per the CommonsWare comment you can use EXTRA_OUTPUT like this:
private void capturePhoto() {
File root = new File(Environment.getExternalStorageDirectory(), "Folder");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, "filename.jpeg");
Uri outputFileUri = Uri.fromFile(file);
Intent photoPickerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(photoPickerIntent, TAKE_PICTURE);
}

Related

Image not saving in folder

I am trying to create a folder and save images in it.
But it's not working.
I don't know what's wrong in my code - can you tell me why?
// The method that invoke of uploading images
public void openGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
File folder = new File(this.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), "albumName");
File file = new File(this.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), "fileName"+3);
Bitmap imageToSave = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Uri selectedImage = data.getData();
Intent i = new Intent(this,
AddImage.class);
i.putExtra("imagePath", selectedImage.toString());
startActivity(i);
}
edit
final File path =
Environment.getExternalStoragePublicDirectory
(
// Environment.DIRECTORY_PICTURES + "/ss/"
//Environment.DIRECTORY_DCIM
Environment.DIRECTORY_DCIM + "/MyFolderName/"
);
// Make sure the Pictures directory exists.
if(!path.exists())
{
path.mkdirs();
}
Bitmap imageToSave = (Bitmap) data.getExtras().get("data");
final File file = new File(path, "file" + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(path);
final BufferedOutputStream bos = new BufferedOutputStream(fos, 8192);
FileOutputStream out = new FileOutputStream(path);
//fos = new FileOutputStream(path);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
// imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
How I do make the folder in DCIM and create a file there into:
/*
Create a path where we will place our picture in the user's public
pictures directory. Note that you should be careful about what you
place here, since the user often manages these files.
For pictures and other media owned by the application, consider
Context.getExternalMediaDir().
*/
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
//Environment.DIRECTORY_DCIM
Environment.DIRECTORY_DCIM + "/MyFolderName/"
);
// Make sure the Pictures directory exists.
if(!path.exists())
{
path.mkdirs();
}
final File file = new File(path, fileJPG + ".jpg");
try
{
final FileOutputStream fos = new FileOutputStream(file);
final BufferedOutputStream bos = new BufferedOutputStream(fos, 8192);
//bmp.compress(CompressFormat.JPEG, 100, bos);
bmp.compress(CompressFormat.JPEG, 85, bos);
bos.flush();
bos.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
fileJPG is the file name I'm creating (dynamically, adding a date).
Replace MyFolderName with albumName.
bmp is my Bitmap data (a screenshot, in my case).
i take a long time for this faking error too and finally it's solve just with add this one line code in manifest
android:requestLegacyExternalStorage="true"

How can i save the image taken from camera intent to be used as a profile image?

In my app the user can take an image from the camera and use as a profile picture. Everything works, except that when the user leaves the app and returns then the image isn't there anymore. So how can I save that image to stay there even when the user exits the app?
Code for camera intent:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
And onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
getLayoutInflater().inflate(R.layout.custon_header,null);
ImageView profimg = (ImageView) findViewById(R.id.roundedimg);
profimg.setImageBitmap(photo);
Could someone please assist me with this?
Thanks
data.getExtras().get("data");
only returns the thumbnail of the image which would be on low quality. You have to specify on your camera intent a location where the image will be saved:
File outputFile = new File(Environment.getExternalStorageDirectory() +"/myOutput.jpg");
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(Intent.EXTRA_OUTPUT,outputFile.getAbsolutePath());
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and on your activityResult, simply use the outputfile for your bitmap:
bitmap = BitmapFactory.decodeFile(outputFile.getAbsolutePath());
You can configure the intent to store the image, using EXTRA_OUTPUT like this:
Intent imageIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
File imageFolder = new File(Environment
.getExternalStorageDirectory(), "YourFolderName");
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
File imageFile = new File(imagesFolder, "user.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
imageIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
activity.startActivityForResult(imageIntent, CAMERA_REQUEST);
So you have the path and can decode the file to bitmap.
You need to save that image in sd-card or phone memory so that it can be accessed when you open your app again. You are seeing that image as soon as you take the image because it is there in the memory and as soon as you leave the app, the memory is released.
private void SaveBitmapInDirectory(Bitmap bitmap, String fileName)
{
File direct = new File(Environment.getExternalStorageDirectory() + "/dirName");
if (!direct.exists())
{
File profilePic = new File("/sdcard/dirName/");
profilePic.mkdirs();
}
File file = new File(new File("/sdcard/dirName/"), fileName);
if (file.exists())
{
file.delete();
}
try
{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
And load the file from directory in onCreate function by calling the following function:
void loadProfilerImage(String fileName)
{
File file = new File(new File("/sdcard/dirName/"), fileName);
if (file.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView.setImageBitmap(myBitmap);
}
}

Creating base64 encoded JPG string from image from camera for upload

I am building an Android app that takes photos, then uploads them to a Rails API.
The api expects the base64 encoded raw file bytes, to be stored as a temp file representing the image in JPG format.
However, the API is rejecting the uploaded file with this error message:
<Paperclip::Errors::NotIdentifiedByImageMagickError:
This seems to be due to a failure of encoding on the part of the Android app.
The base64 image bytes that I'm sending up look like this:
Which appears invalid just by looking at it.
The image is created in android by taking a pic with the Camera API and base64 encoding the resulting byteArray:
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Anyone know what I'm doing wrong here?
On button click for capturing an image from a camera use this
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));
((Activity) context).startActivityForResult(intent, Constants.REQUEST_IMAGE_CAPTURE);
and on activityResult of the activity implement the following code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final ImageView uploadArea = (ImageView) attachmentDialog.findViewById(R.id.uploadArea);
Bitmap bitmap;
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] attachmentBytes = byteArrayOutputStream.toByteArray();
String attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);
uploadArea.setImageBitmap(rotatedBitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "CTSTemp" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I hope this will help you, and for any farther info, please ask

save picture in new directory

i want too save images in my own directory this is perhaps the directory on which the images are been saved
Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
and this is were i am giving my image uri Target where the image will going to be save
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
how can i achive that by making my own directory and saving image there
Hi I would liked to share the method to create and Save the Images in Your Custom Directory as follows :
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You should supply the Bitmap Object to be saved and the Directory Name in which You want to Save as follows :
createDirectoryAndSaveFile(imageToSave,fileName);
I have tried to take a picture and then crop it then stored it on SDCard. Here are codes, maybe you will be inspired:
Take a photo:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(AVATAR_FILE_TMP));
intent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, CODE_TAKE_PHOTO);
Then crop the photo:
if (requestCode == CODE_TAKE_PHOTO) {
cropImage(Uri.fromFile(AVATAR_FILE_TMP));
}
public void cropImage(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 400);
intent.putExtra("outputY", 400);
intent.putExtra("return-data", true);
startActivityForResult(intent, CODE_CROP_IMAGE);
}
And at last, store the picture:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
// civAvatar.setImageBitmap(photo); // 把图片显示在ImageView控件上
FileOutputStream fos = null;
try {
// store the picture
fos = new FileOutputStream(AVATAR_FILE);
photo.compress(Bitmap.CompressFormat.PNG, 100, fos);// (0-100)compress file.
AVATAR_FILE_TMP.deleteOnExit();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
IoUtils.closeSilently(fos);
finish();
}
}
And if you just store the picture, intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(AVATAR_FILE_TMP)); is OK.
The solution involving heavy Bitmaps is (IMHO) irrelevant when your phone or camera is taking JPEGs.
See the solution here for an almost instantaneous solution: https://stackoverflow.com/a/7982964/5426777
new FileOutputStream(myPath).write(byte[] myPictureCallbackBytes)

take and save picture with specified size (in KB-s)

in my app I take a picture and save it in specified way. My phone is Nexus 4 and the camera is very strong and every picture is about 2.31MB how can I save picture for example in 60KB?
Can I do it with code? and how?
File newdir = new File(dir);
if(!newdir.exists()){
newdir.mkdirs();
}
picturesCount++;
String file = dir+picturesCount+".jpg";
imagePath = file;
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
When you are using camera and picture is taken, you can perform the task in the method below to reduce the quality of the image and type like JPEG or PNG (PNG takes more space than JPEG) so just play with the value (60 current out of 100) and see the difference in size.
#Override
public void onPictureTaken(byte[] data, Camera camera) {
InputStream in = new ByteArrayInputStream(data);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap preview_bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
preview_bitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
byte[] byteArray = stream.toByteArray();
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(new File(
Environment.getExternalStorageDirectory(), "Image1.jpg"));
outStream.write(byteArray);
outStream.close();
} catch (FileNotFoundException e) {
Log.d("CAMERA", e.getMessage());
} catch (IOException e) {
Log.d("CAMERA", e.getMessage());
}
}

Categories

Resources