Efficient way to send data onActivityResult to another activity - java

So I want to load an image from gallery with overriding onActivityResult . What is an efficient way to send intent data to another activity?
Currently using this code to to get image path before sending it to the other activity:
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selected_image = data.getData();
if (selected_image.toString().substring(0, 21).equals("content://com.android")) {
String[] photo_split = selected_image.toString().split("%3A");
String imageUriBasePath = "content://media/external/images/media/" + photo_split[1];
selected_image = Uri.parse(imageUriBasePath);
}
String[] file_path_column = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selected_image, file_path_column, null, null, null);
cursor.moveToFirst();
int column_index = cursor.getColumnIndex(file_path_column[0]);
image_path = cursor.getString(column_index);
cursor.close();
Intent intent = new Intent(MainActivity.this, ImageActivity.class);
intent.putExtra("imagePath", image_path);
startActivity(intent);
}
}
The problem is that this code does not seem to work in a good way, since after selecting an image from gallery app, the gallery lags for few seconds before loading the image into the other activity.

Try this, following is for getting image from both camera and gallery:
ImageView photo;
Bitmap bmp;
static int GET_PICTURE = 1, CAMERA_PIC_REQUEST = 2;
static String selectedImagePath = "";
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
// deleteDialog.dismiss();
bmp = (Bitmap) data.getExtras().get("data");
} else if (requestCode == GET_PICTURE) {
if (bmp != null) {
bmp.recycle();
}
// deleteDialog.dismiss();
Uri selectedImageUri = data.getData();
selectedImagePath = getRealPathFromURI(selectedImageUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
options.inSampleSize = calculateInSampleSize(options, 200,
200);
options.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(selectedImagePath, options);
}
if (bmp != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Bitmap outputs = getRoundedBitmap(bmp,10);
last = Bitmap.createScaledBitmap(outputs, 200, 200, false);
if (last != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
last.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
photo.setImageBitmap(last);
// userimage.setBackgroundResource(android.R.color.transparent);
}
} else {
Toast.makeText(getBaseContext(), "Invalid image",
Toast.LENGTH_SHORT).show();
}
}
}
public static Bitmap getRoundedBitmap(Bitmap bitmap,int pixels) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
//canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null,
null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor
.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
}
cursor.close();
return result;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}

// Opening gallery
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Keys.PICTURE_REQ_CODE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
// Gallery
case Keys.PICTURE_REQ_CODE:
Uri fileUri = data.getData();
cropIntent = new Intent(this,CropActivity.class);
cropIntent.setData(fileUri);
startActivityForResult(cropIntent,Keys.CROP_REQ_CODE);
break;
}
}
}

Related

How to fix degree of image rotation after take image from front camera and back camera in android?

after take image from camera this image rotate with tow different degree between front camera and back camera I tried add rotation to image after take image from camera but it doesn't work with all devices by the same degree .
Note : I added face recognition but it doesn't work when images rotate,this is my code .
public class CheckIn extends AppCompatActivity {
private ImageView camera;
String encoded = "";
byte[] byteArray;
static final int REQUEST_IMAGE_CAPTURE = 1;
private Button checkIn;
ContentValues values;
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
Uri imageUri;
Bitmap thumbnail;
SparseArray<Face> faces ;
Matrix matrix ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_in);
camera = (ImageView) findViewById(R.id.camera);
checkIn = (Button) findViewById(R.id.submit);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
});
checkPermissionREAD_EXTERNAL_STORAGE(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
if(Build.VERSION.SDK_INT >= 27) {
//only api 27 above
matrix = new Matrix();
matrix.postRotate(90);
}else{
//only api 27 down
matrix = new Matrix();
matrix.postRotate(270);
}
Bitmap rotatedBitmap = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap converetdImage = getResizedBitmap(rotatedBitmap, 700);
converetdImage.compress(Bitmap.CompressFormat.PNG, 10, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
RequestOptions options = new RequestOptions()
.centerCrop()
.placeholder(R.mipmap.ic_launcher_round)
.error(R.mipmap.ic_launcher_round);
Paint myRectPaint = new Paint();
myRectPaint.setStrokeWidth(5);
myRectPaint.setColor(Color.RED);
myRectPaint.setStyle(Paint.Style.STROKE);
Bitmap tempBitmap = Bitmap.createBitmap(rotatedBitmap.getWidth(), rotatedBitmap.getHeight(),
Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(rotatedBitmap, 0, 0, null);
FaceDetector faceDetector
= new
FaceDetector.Builder(getApplicationContext()).setTrackingEnabled(false)
.build();
Frame frame = new Frame.Builder().setBitmap(rotatedBitmap).build();
faces = faceDetector.detect(frame);
for (int i = 0; i < faces.size(); i++) {
Face thisFace = faces.valueAt(i);
float x1 = thisFace.getPosition().x;
float y1 = thisFace.getPosition().y;
float x2 = x1 + thisFace.getWidth();
float y2 = y1 + thisFace.getHeight();
tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint);
}
Glide.with(CheckIn.this).load(tempBitmap).apply(options)
.into(camera);
} catch (Exception e) {
e.printStackTrace();
} }
}
public void checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
// Enable if permission granted
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) {
}
// Else ask for permission
else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
}
thanks in advance .
try this please
i just have to add
camera.setDisplayOrientation(90);
now the display is on the right angle.

RecyclerView take Image form camera is rotating when show on the list

I have an issue with my code. When I take a photo from my app, it is rotating 90ยบ to show. But, when I choose gallery option to select my photo, it is showing normal.
Can someone help me??
Code bellow:
Adapter.java
public void onBindViewHolder(#NonNull final ProdutosListaViewHolder holder, final int i){
Produto prod = produtos.get(i);
File foto = mPicture.getImageProduto(prod.codProd);
if(foto == null || foto.exists()){
holder.foto.setImageResource(R.drawable.sem_foto_icon);
}else{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeFile(foto.getAbsolutePath(), options);
holder.foto.setImageBitmap(bitmap);
}
}
PictureManager.java
if the camera selected to take the photo
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(ctx, ....));
((Activity) ctx).startActivityForResult(i, 999);
if the gallery selected to take the photo
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity) ctx).startActivityForResult(i, 998);
ProductListActivity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==999){
try{
File foto = (new PictureManager(FOTO_PRODUTO, ctx)).getImageProduto(produtoSelecionado.codProd);
if(foto != null){
mProdutosListaAdapter.notifyItemChanged(posicaoSelecionada);
}
}catch(Exception e){
e.printStackTrace();
}
}else if(requestCode==998){
try{
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = ctx.getContentResolver().query(selectedImage, filePathColumn, null null, null);
cursor.moveToFirst();
int columnIndex = cursor.ColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
File file = new File(picturePath);
int codigo = produtoSelecionado.codProd;
File foto = (new PictureManager(FOTO_PRODUTO, ctx)).salvarFoto(file, codigo, 1);
mProdutosListaAdapter.notifyDataSetChanged();
}
}
}
}
}
Camera always gives you the picture according to camera orientation. I have tried the below code to change orientation
public static Bitmap rotateImageOrientation(String photoFilePath) {
// Create and configure BitmapFactory
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoFilePath, bounds);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(photoFilePath, opts);
// Read EXIF Data
ExifInterface exif = null;
try {
exif = new ExifInterface(photoFilePath);
} catch (IOException e) {
e.printStackTrace();
}
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;
// Rotate Bitmap
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
return Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
// Return result
}

Blank white screen when trying to capture an image and set in imageView

I'm trying to capture an image and set in imageView, like in this code that someone in stackoverflow offered, but i get blank white screen.
what could be the problem?
thanks.
private String pictureImagePath = "";
private void openBackCamera() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
File file = new File(pictureImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 1);
}
Handle Image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
File imgFile = new File(pictureImagePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
}
Here's the code I used to get bitmap's to display within an ImageView (sorry it's in MonoDroid/C#, it will require light modification to work in Android/Java):
using System.IO;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Widget;
namespace MyApp.Util
{
public static class BitmapHelpers
{
/// <summary>
/// This method will recyle the memory help by a bitmap in an ImageView
/// </summary>
/// <param name="imageView">Image view.</param>
public static void RecycleBitmap(this ImageView imageView)
{
if (imageView == null) {
return;
}
Drawable toRecycle = imageView.Drawable;
if (toRecycle != null) {
((BitmapDrawable)toRecycle).Bitmap.Recycle ();
}
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
int height = options.OutHeight;
int width = options.OutWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
int halfHeight = height / 2;
int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
/// <summary>
/// Load the image from the device, and resize it to the specified dimensions.
/// </summary>
/// <returns>The and resize bitmap.</returns>
/// <param name="fileName">File name.</param>
/// <param name="width">Width.</param>
/// <param name="height">Height.</param>
public static Bitmap LoadAndResizeBitmap(this string fileName, int width, int height)
{
// First we get the the dimensions of the file on disk
BitmapFactory.Options options = new BitmapFactory.Options
{
InPurgeable = true,
InJustDecodeBounds = true
};
BitmapFactory.DecodeFile(fileName, options);
options.InSampleSize = calculateInSampleSize(options, width, height);
options.InJustDecodeBounds = false;
Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options);
return resizedBitmap;
}
}
}
Example Usage
public static Bitmap LoadBitmap( File imageFile, int w, int h )
{
Bitmap bitmap = null;
if (imageFile != null)
{
if( (new File(imageFile.Path)).Exists() )
{
bitmap = imageFile.Path.LoadAndResizeBitmap(w, h);
}
}
return bitmap;
}
OnActivityResult Snippet (Makes picture available in Gallery)
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
switch ((ActivityRequestCode)requestCode)
{
case ActivityRequestCode.Camera:
// make it available in the gallery
if (_imageFile != null)
{
Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
Uri contentUri = Uri.FromFile(_imageFile);
mediaScanIntent.SetData(contentUri);
SendBroadcast(mediaScanIntent);
_pictureRequestingFragment.PictureReady(_imageFile);
}
break;
case ActivityRequestCode.Map:
break;
}
}

ImageView remains blank, Android

I am allowing user to choose image and using it to set as imageview in another activity. But the imageview remains blank. Following is my code.
private static final int REQUEST_CODE_GALLERY = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
public ImageView CameraButton;
public ImageView GalleryButton;
public ImageView example;
public Bitmap imageBitmap;
public Bitmap bmp;
ongallery object = new ongallery();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GalleryButton = (ImageView) findViewById(R.id.GalleryButton);
CameraButton = (ImageView) findViewById(R.id.CameraButton);
example = (ImageView) findViewById(R.id.example);
GalleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, REQUEST_CODE_GALLERY);
}
});
CameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (camera.resolveActivity(getPackageManager()) != null) {
startActivityForResult(camera, REQUEST_IMAGE_CAPTURE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && null != data) {
Uri chosen = data.getData();
String[] filepath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(chosen, filepath, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filepath[0]);
String photoadd = cursor.getString(columnIndex);
cursor.close();
bmp = BitmapFactory.decodeFile(photoadd);
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(this, ongallery.class);
in1.putExtra("picture", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK && null!=data) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
photo.recycle();
//Pop intent
Intent in1 = new Intent(this, ongallery.class);
in1.putExtra("picture", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
}catch(Exception e){
Toast.makeText(this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
}
}
//ongallery.java
public class ongallery extends Activity {
public ImageView imgView;
int xDim;
int yDim;
String filename;
public Bitmap finale = null ;
public Bitmap bmp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ongallery);
imgView = (ImageView) findViewById(R.id.imgView);
filename = getIntent().getStringExtra("picture");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
imgView.setImageBitmap(decoder(filename,400,400));
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
xDim=imgView.getWidth();
yDim=imgView.getHeight();
}
public Bitmap decoder(String filename, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
finale = BitmapFactory.decodeFile(filename, options);
return finale;
}
int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) {
int inSampleSize = 1;
if (options.outHeight > reqHeight || options.outWidth > reqWidth) {
final int halfHeight = options.outHeight / 2;
final int halfWidth = options.outWidth / 2;
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) >reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
BitmapFactory.decodeFile() needs the complete path name as the first argument.
public Bitmap decoder(String filename, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
String filepath = getFileStreamPath(filename).getPath();
BitmapFactory.decodeFile(filepath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
finale = BitmapFactory.decodeFile(filepath, options);
return finale;
}

Android Studio Camera App Saving to Internal Storage

Currently looking for help on saving images from a camera app to internal storage do to Nexus not having an SD card, our current code saves the photos taken to an SD card folder and the quality is not good.
public class MainActivity extends ActionBarActivity {
private ImageView imageHolder;
private final int requestCode = 20;
public final static String EXTRA_MESSAGE = "com.test1.cam.camapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
// display the image from SD Card to ImageView Control
String storeFilename = "photo_" + partFilename + ".jpg";
Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
imageHolder.setImageBitmap(mBitmap);
}
}
public void showGreetings(View view)
{
String button_text;
button_text = ((Button) view) .getText().toString();
if(button_text.equals("Info"))
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
else if (button_text.equals("Info"))
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
public void saveImage(Context context, Bitmap b,String name,String extension){
name=name+"."+extension;
FileOutputStream out;
try {
out = context.openFileOutput(name, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap getImageFileFromSDCard(String filename){
Bitmap bitmap = null;
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
try {
FileInputStream fis = new FileInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
To improve the image quality you should change compression to PNG, or change the second parameters to 100 (PNG is lossless and will ignore second params).
b.compress(Bitmap.CompressFormat.PNG, 100, out);
To change external into internal just change
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
into
File outputFile = new File(context.getFilesDir(), "photo_" + currentDate + ".jpg");
The image you are trying to save returns you jest the thumbnail of the actual image that is why you are getting low quality image. You should pass the image name to the intent to save the high quality image when it is captured
Following Helper class that I use for image capture may be of some help to you
public class CaptureImageHelper {
private static final int DEFAULT_WIDTH = 1024; // min pixels
private static final int DEFAULT_HEIGHT = 768; // min pixels
private static final String TEMP_IMAGE_NAME = "tempImage";
public static Intent getImageCaptureIntent(Context context, String title) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1), title);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
private static File getTempFile(Context context) {
//Note you can change the path here according to your need
File imageFile = new File(Environment.getExternalStorageDirectory(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
list.add(targetedIntent);
}
return list;
}
public static Bitmap getImageFromResult(Context context, int resultCode, Intent imageReturnedIntent) {
return getImageFromResult(context, DEFAULT_WIDTH, DEFAULT_HEIGHT, resultCode, imageReturnedIntent);
}
public static Bitmap getImageFromResult(Context context, int width, int height, int resultCode, Intent imageReturnedIntent) {
Bitmap bm = null;
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage;
File imageFile = getTempFile(context);
selectedImage = Uri.fromFile(imageFile);
bm = getImageResized(context, selectedImage, width, height);
int rotation = getRotation(context, selectedImage, true);
bm = rotate(bm, rotation);
}
return bm;
}
private static Bitmap getImageResized(Context context, Uri selectedImage, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
System.gc();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap actuallyUsableBitmap = null;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
} catch (FileNotFoundException e) {
}
if (null != fileDescriptor) {
BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
}
return actuallyUsableBitmap;
}
private static Bitmap getImageResized(Context context, Uri selectedImage) {
return getImageResized(context, selectedImage, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private static int getRotation(Context context, Uri imageUri, boolean isCamera) {
int rotation;
if (isCamera) {
rotation = getRotationFromCamera(context, imageUri);
} else {
rotation = getRotationFromGallery(context, imageUri);
}
return rotation;
}
private static int getRotationFromCamera(Context context, Uri imageFile) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageFile, null);
ExifInterface exif = new ExifInterface(imageFile.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
private static int getRotationFromGallery(Context context, Uri imageUri) {
int orientation = 0;
String[] columns = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (null != cursor && cursor.moveToFirst()) {
int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
orientation = cursor.getInt(orientationColumnIndex);
cursor.close();
}
return orientation;
}
private static Bitmap rotate(Bitmap bm, int rotation) {
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
}
return bm;
}
}

Categories

Resources