Getting a crash when taking a picture on Android. Why? - java

When I take a picture with my device, this code is crashing on the inputStream = line with an error of java.lang.NullPointerException
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriImage;
InputStream inputStream = null;
ImageView imvCover = (ImageView)this.findViewById(R.id.imvCover);
if ((requestCode == CAPTURE_IMAGE) && resultCode == Activity.RESULT_OK) {
uriImage = data.getData();
try {
inputStream = getContentResolver().openInputStream(uriImage);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, null);
imvCover.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
imvCover.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imvCover.setAdjustViewBounds(true);
}
}
Any ideas why?
This is the code I am using to open the camera to take a picture:
Button btnTakePicture = (Button)this.findViewById(R.id.btnTakePicture);
btnTakePicture.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE);
}
});

try this..
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, "newImage.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
startActivityForResult(i, 1);
and this is onActivity result..
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent)
{
super.onActivityResult(requestCode, resultcode, intent);
File out = new File(Environment.getExternalStorageDirectory(), "newImage.jpg");
if(!out.exists())
{
Log.v("log", "file not found");
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Log.v("log", "file "+out.getAbsolutePath());
File f = new File(out.getAbsolutePath());
try {
ExifInterface exif = new ExifInterface(out.getAbsolutePath());
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
//Toast.makeText(getApplicationContext(), ""+orientation, 1).show();
Log.v("log", "ort is "+orientation);
} catch (IOException e)
{
e.printStackTrace();
}
Bitmap photo =decodeFile(f,400,400);
}
and this is decodeFile Function...
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}

This approach may not work for all devices. Instead, you can specify where the new image would be saved, and then you can use that pre-determined file path to work with the new image.
File tempFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/your_folder");
tempFolder.mkdir();
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/your_folder", String.valueOf(System.currentTimeMillis()) + ".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, TAKE_PICTURE);

Related

Android Large Image on Imageview Crashes App on OOM Error

The below code allows a user to pick 4 images from their gallery and upload to a server. At the moment It is uploading all 4 small images but when i try large images it crashes on OOM error.
Even when i try to load 2 large images the app crashes when i load a big images on OOM error. What is the most efficient way to handle such issues?. I have read this Android Bitmaps but i don't seem to get how to implement in my four images code. I have tried Picasso but the app still behaves the same (ditto) above.
SelectImageGallery1 = (Button)findViewById(R.id.buttonSelect1);
SelectImageGallery2 = (Button)findViewById(R.id.buttonSelect2);
SelectImageGallery3 = (Button)findViewById(R.id.buttonSelect3);
SelectImageGallery4 = (Button)findViewById(R.id.buttonSelect4);
UploadImageServer = (Button)findViewById(R.id.buttonUpload);
SelectImageGallery1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image1 From Gallery"), 1);
}
});
SelectImageGallery2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image4 From Gallery"), 2);
}
});
SelectImageGallery3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image3 From Gallery"), 3);
}
});
SelectImageGallery4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image4 From Gallery"), 4);
}
});
UploadImageServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetImageNameEditText1 = imageName1.getText().toString();
GetImageNameEditText2 = imageName2.getText().toString();
GetImageNameEditText3 = imageName3.getText().toString();
GetImageNameEditText4 = imageName4.getText().toString();
ImageUploadToServerFunction();
}
});
}
#Override
protected void onActivityResult(int RC, int RQC, Intent I) {
super.onActivityResult(RC, RQC, I);
if (RC == 1&&RQC == RESULT_OK&&I != null&&I.getData() != null) {
Uri uri = I.getData();
try {
bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView1.setImageBitmap(bitmap1);
} catch (IOException e) {
e.printStackTrace();
}
}
if (RC == 2 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView2.setImageBitmap(bitmap2);
} catch (IOException e) {
e.printStackTrace();
}
}
if (RC == 3 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
byte[] imageAsBytes=null;
try {
bitmap3 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView3.setImageBitmap(bitmap3);
} catch (IOException e) {
e.printStackTrace();
}
}
if (RC == 4 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
bitmap4 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView4.setImageBitmap(bitmap4);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage1(Bitmap bitmap1){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage1 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage1;
}
public String getStringImage2(Bitmap bitmap2){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage2 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage2;
}
public String getStringImage3(Bitmap bitmap3){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap3.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage3 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage3;
}
public String getStringImage4(Bitmap bitmap4){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap4.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage4 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage4;
}
This was achieved by using Glide as follows. Using glide ensures the OOM errors are handled and they are not repeated on loading even a 30mb image.
#Override
protected void onActivityResult(int RC, int RQC, Intent I) {
super.onActivityResult(RC, RQC, I);
if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
RequestOptions options = new RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.placeholder(R.drawable.ic_launcher_background)
.error(R.drawable.ic_launcher_background);
Glide.with(this)
.setDefaultRequestOptions(options)
.asBitmap()
.load(uri)
.centerInside()
.into(new CustomTarget<Bitmap>(512, 512) {
#Override
public void onResourceReady(#NonNull Bitmap bitmap1, #Nullable Transition<? super Bitmap> transition) {
imageView1.setImageBitmap(bitmap1);
UploadActivity.this.bitmap1 = bitmap1;
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
}
ByteArrayOutputStream holds all data in memory. So you cannot store data larger than the heap. Modify the "manifest" in the first way.
AndroidManifest.xml
<application
android:largeHeap="true">
</application>
Use FileInputStream instead of ByteArrayOutputStream.
You should decode bitmap to decrease the size of bitmap before upload to sever:
You can change size(reqWidth\reqHeight) at your disposal
You can refer to my Github to get full code: https://github.com/vancuong0429/ResizeImageUtil/blob/master/ResizeImageUtil
To get a file from onActivityResult(), You can refer link
Android Studio get File from Gallery Intent
In onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
// Creating file
// Get the path from the Uri
final String path = getPathFromURI(uri);
if (path != null) {
File yourFile = new File(path);
bitmap1 = decodeBitmapFromFile(yourFile, 512, 512)
}
}
}
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null,
null, null);
if (cursor.moveToFirst()) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
fun decodeBitmapFromFile(imageFile: File, reqWidth: Int, reqHeight: Int): Bitmap {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(imageFile.absolutePath, options)
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight)
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false
var scaledBitmap = BitmapFactory.decodeFile(imageFile.absolutePath, options)
scaledBitmap = modifyOrientation(scaledBitmap, imageFile.absolutePath)
return scaledBitmap
}

Cannot upload image file using retrofit2

Problem with old code, image sending to server is thumbnail image (so small). So with new code, Android has changed the way to get real size image. However, new code not working upload file to the server. It says filename is empty and when I do log body request not the same result as the old code. Any help, I really appreciate because almost one week I still couldn't found what is the problem with the new code.
///////// This is old cold//////////////////////////////////
///////////////////////////////////////////////////////////
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
switch (resultCode) {
case Activity.RESULT_CANCELED: {
break;
}
case Activity.RESULT_OK: {
if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, bytes);
if (typePhoto.equals("ftCarLol")) {
carLoL = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + "ftLol.png");
FileOutputStream fo = null;
try {
carLoL.createNewFile();
fo = new FileOutputStream(carLoL);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ftCar.setImageBitmap(thumbnail);
}
if (typePhoto.equals("sdcarLol")) {
sdCad = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + "sdCars.png");
FileOutputStream fo = null;
try {
sdCad.createNewFile();
fo = new FileOutputStream(sdCad);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sdCar.setImageBitmap(thumbnail);
}
}
break;
}
}
}
}
// in retrofit
MultipartBody.Part[] imageUserList = new MultipartBody.Part[2];
RequestBody propertyImage = null;for(
int i = 0;i<2;i++)
{
if (i == 0) {
propertyImage = RequestBody.create(MediaType.parse("image/*"), carLoL);
imageUserList[i] = MultipartBody.Part.createFormData("car", carLoL.getName(), propertyImage);
}
if (i == 1) {
propertyImage = RequestBody.create(MediaType.parse("image/*"), sdCad);
imageUserList[i] = MultipartBody.Part.createFormData("sd", sdCad.getName(), propertyImage);
}
}
// Call function interface retrofit
Call<JsonObject> clientreq = client.submitReport(imageUserList);
// interface retrofit
#Multipart
#POST("TestReport")
Call<JsonObject>submitReport(#Part MultipartBody.Part[] files);
/////////////////////// new code////////////////////////////////////
File tempFile = new File(Environment.getExternalStorageDirectory(), "tmp.png");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri photoURI = FileProvider.getUriForFile(this, "cntsb.com.rodeo.fileprovider", tempFile);
// result activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
if (typeChoose.equals("sdcarLol")) {
sdCad = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() +"sdCars.png");
try {
sdCad.createNewFile();
if(tempFile.renameTo(sdCad)) {
Glide.with(context).load(sdCad).into(sdCar);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (typeChoose.equals("ftCarLol")){
carLoL = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + "ftLol.png");
try {
carLoL.createNewFile();
if(tempFile.renameTo(carLoL)) {
Glide.with(context).load(carLoL).into(ftCar);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// attach file into retrofit
MultipartBody.Part[] imageUserList = new MultipartBody.Part[2];
RequestBody propertyImage = null;for(
int i = 0;i<2;i++)
{
if (i == 0) {
propertyImage = RequestBody.create(MediaType.parse("image/*"), carLoL);
imageUserList[i] = MultipartBody.Part.createFormData("car", carLoL.getName(), propertyImage);
}
if (i == 1) {
propertyImage = RequestBody.create(MediaType.parse("image/*"), sdCad);
imageUserList[i] = MultipartBody.Part.createFormData("sd", sdCad.getName(), propertyImage);
}
}
// Call function interface retrofit
Call<JsonObject> clientreq = client.submitReport(imageUserList);
Expected result: after log request body
�PNG
������IHDR��������������������}��������s��O����� ��IDATx�\�k�d�q%�wĹ7���h4��B$%R�F������|�G�k��g$��z-{F=H�C
$�#t��g>�9��f������2o�s"b��;��/�o�&�Hp��)��4�l��gs�� � ��I#FdN�'l9�ۭ��� �� ejb�H�q��,��':Jw�D)`�4�"ő 3#9��Lg���d LF���f:߸5O��L�bhn��HN�$) !�$�dDЍ�� -F���e0E)�� ��[r$DP���6� �����߼T��4���1�`��+4�$M���%s�sR�L�� ��B�D2�������$Ѥ$������RRԚ.cDv����[(3����R�Df�9:"a23R!����"!)��BL�dfRQ[��C��jl����{}�e9�
e�0���s(d�T��H)QR(���H#fX����)���Hm2(Aa�C��$��i6��"�%q������LfI(�F���Zf�$
�d2If�0���Y�LF����`��D$pGI����(364��6�eO���#dD$֣�Ӻ�0�$IA����[I!���'LI��9�#i֤>ƨ?���0��ʡ��&��4$��DMn�.�ljH���IR��
4 �9���PH��ƒ#D�4��͐��#�Y��]Rf���1s�� $�"I�� ��c����7)3��f���xR�C)i$���U�X�}u�ZSw�il��H��`��吹�:��mM +����m�z���S(�XX'֜Z�f�3#!�)I�"�#��ެ>�c���i�����E��S��d(33"�9���tw%ͽ��H2I�9J)�C���$Ț�2�L$��ȔxX��K
�<7��4�S��H&epI�j�Բ�1z��L���b����\c��`��\?�H�jM�0� R# ��|<Q� QI���6ײ$է����j�"S�,��?u���D���zI8��f����ˈTD�ߎr��_=�`��3��H��˼2���I!����5nͥ�+�Y�uְnF=���~`�B��״�`մ�����̬MDssw�%2s�NfBf(qJ
ID�2S\�HV�!����R�Z��Hef�H�8��z�ua���4��:H�Q{��t�Uj�I1���_V����#!AEJ
[��CffHO������jwk�!���5�CT؀��E���,c�/���:��rN��`����#B���<������ʢ���썭��YYE�)V��9�R6�f��4�$ dB0�U3SF��f�����X���FV
��1tJ5\��tk���VxT�S��������&V4��I�H4d��LO���.h*#�))���M-s���&#33���$d3I$�m=�`m�d�/��{�`)���
=��F���L3�H$��4��gIt��Ar#f03�G�q%Y�N#~ʼv�1�̯���I2��HZq2m�me��!i2.�RI�S$h(�5��R�����5���wP�ҪC8�^>��S�]SY�##��i�TbG�g2bT:�F Ɍ��&o�H`>��pnI�Ԛ(��
4dk�"N�i$�4{%h"Sn�Ќ��D�ZkUN��{���z�#����4k
dB��[Y(C��I��if ������tx%n���kMO�I��Lr�(�=�ehHLA9F0*��V(\�����2S^�B��$�.)B�QHiD׊�(�*kם�4M����H�9�fNfV+r
���(�16�R���.<ǪRF�,�d$92��aP��.#����ښ"ift0:�)�ܽ���G�&�(d_�H+df���j�)��7���$Vk���(#9MS5v�d�zP�� ��BdJ�1����D���ٚ�����z�2�#��c��UxQh6R˲��N�iE�nS��s��Tݵ��#DdF��C'��D�<��$��܎J0��׏��^ߨ�s��ڒ��C�bD�y������I��֚Y�#�� ���������" #LU!Y����53W�!L2m����U�Y��(xM2�R�A�jg�v*���6W:�r��jX$�6RZѝ5�t��)��<G��BM(Y����y��7��c���2N��R�1WT`�٦*�IV�è����D�Ĝ���2��^ �8U�GkE�$��N8
(���hk/�#��3�nS�5�g��r<���ՙ����0�<���}D�,�Wi#�P�t�$ִ����0"j����D��
error from new code:
����A2Exif����MM��*�����������������������������������������������������������������������������������������������������������������������������(��������������1���������������2������������������������������i����������������!8HUAWEI����DUK-L09��������H������������H������DUK-L09 9.0.1.176(C636E2R1P5)�����2019:07:04 10:46:13����.��������������������������������P�������������� ʈ"���������������'������������������������0210������������� ڐ������������ ������������������������ ��
����������X������������� Ғ��
����������#���
����������H������������� ������������������������������� ���������������
������������0�|��������d���� N�|����������� ��|��������/�������|�����������`�|������������ H��������������!��������������!
��������������!�����������0100��������������������������������������������������������!�������������������������������������������������������������������������������������������������������������8������������������������������������������������������������������ �����������������
����������������������������������������������������������d������d����������������������������
����;������������'#*#*201709272016::76������/��`����������DLBB8�}N�������������������::76������/��`����������DLBB8�}N�������������������::76������/��`����������DLBB8�}N�������������������::54������/��`�����#����AIBB8�wN�������������������::54����/����`�����#����AIBB8�wN�������������������::54����/����`�����#����AIBB8�wN�������������������::2����.����`�����#����=EBB8�rN�������������������::0/������-��`�����#����:CBB8�oN��������������������� ��4����B������������������������������������������275��h����� ��+����j^SJC>93+$m_TKD?:4,%o`ULE?:4-%qbVME?:5.&sdWMF#;7/' ueXMFA=70( vfXNGA=81)!vfYNGB=81)"ufYOGB>92*"teZOHB>:3+#tfZPIC>:4+$tfZQIC>:4,$sfZRJD>:4,%qdZRJD?:4-%odZQJD?:5-&mcYQJD?:5.&������������������������������������������������������������������������������������:�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������J���#�������������������������������������������x�� �������F��F��������������������������������������� ����������������������*������:����������������������*������:������(��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

Get image from storage not working in Android

I am capturing an image and store it in storage in mobile but when I get this image it cannot show any thing in Image View. I have tried a lot of code to get images from file but none of them are working in my emulator or real Samsung device.
enter code here
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);
}
});
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);
}
}
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; */
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
// File imgFile = new File(filename);
//("/sdcard/Images/test_image.jpg");
Bitmap myBitmap;
if(imageFile.exists()){
myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
// myImage.setImageBitmap(myBitmap);
return myBitmap;
}
return null;
}
First of All make sure you have declared the "Access External Storage" and "Access Hardware Camera" permissions in "AndroidManifest" and if you are using Android version 23 or 23+ then you have to take permissions on run-time.
If this is not the problem then use this code given below, it's working fine for me.
For Camera:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, ACTION_REQUEST_CAMERA);
For Gallery:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent.createChooser(intent, "Choose a Picture");
startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
OnActivityResultMethod:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ACTION_REQUEST_GALLERY:
Uri galleryImageUri = data.getData();
try{
Log.e("Image Path Gallery" , getPath(getActivity() , galleryImageUri));
selectedImagePath = getPath(getActivity() , galleryImageUri);
} catch (Exception ex){
ex.printStackTrace();
Log.e("Image Path Gallery" , galleryImageUri.getPath());
selectedImagePath = galleryImageUri.getPath();
}
break;
case ACTION_REQUEST_CAMERA:
// Uri cameraImageUri = initialURI;
Uri cameraImageUri = data.getData();
Log.e("Image Path Camera" , getPath(cameraImageUri));
selectedImagePath = getPath(cameraImageUri);
break;
}
}
}
Method to get path of Image returned from Camera:
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}

Application crashes after selecting bitmap image from gallery/camera (maybe scaling is solution)

I have an application with an image view, and when i click on it it opens menu of choosing Take From Gallery/ Open Camera.
after i choose a large image (large size or large scaling) the app crashes.
how can i fix it?
this is the code and logcat:
Select image+onActivityResult:
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose From Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
AddContactActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[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, 1);
} else if (options[item].equals("Choose From Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
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 {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imginAdd.setImageBitmap(bitmap);
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream3);
byteArray = stream3.toByteArray();
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + 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.PNG, 100, 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();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap bitmap = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........",
picturePath + "");
imginAdd.setImageBitmap(bitmap);
ByteArrayOutputStream stream4 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream4);
byteArray = stream4.toByteArray();
}
}
}
Getting the image from another through sql:
(4 lines as one code, i have problem with quoting:)
Blockquote byte[] photo = rs.getBlob(rs
.getColumnIndex(DBHelper.CONTACTS_COLUMN_IMAGE));
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
imginView.setImageBitmap(theImage);
LOGCAT: http://textuploader.com/69on
Simply use this function which will decode your large image too.
private void setPic(final String path) {
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
bitmap = BitmapFactory.decodeFile(path, bmOptions);
}
Now call this function after retrieve your image path from gallery
setPic(imagepath);
imageView.setImageBitmap(bitmap); // this bitmap object will be declare globally

How do I save an image after modifying it

I can load the picture to the background then I have also been able to "sketchify" it but when I try to save it so that I can email it as an attachment I can only figure out haw to grab the original image and what I have here makes the activity close
public void startCamera(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
seek.setVisibility(View.GONE);
if (takePicture.resolveActivity(getPackageManager()) != null) {
picSpot = new File(Environment.getExternalStorageDirectory(),
"sketch.png");
outputFileUri = Uri.fromFile(picSpot);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePicture, REQUEST_IMAGE_CAPTURE);
}
}
public void sendPic(View v) {
Intent sharePic = new Intent(Intent.ACTION_SEND);
if (didsketch == false) {
sharePic.setType("image/png");
sharePic.putExtra(Intent.EXTRA_STREAM, outputFileUri);
sharePic.putExtra(Intent.EXTRA_SUBJECT, "Check This Out!");
sharePic.putExtra(Intent.EXTRA_TEXT,
"I did this on my Sketchify App!");
startActivity(Intent.createChooser(sharePic, "Send Email"));
} else {
try {
FileOutputStream out = new FileOutputStream(finalSpot);
back.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
outputFileUri = Uri.fromFile(finalSpot);
sharePic.setType("image/png");
sharePic.putExtra(Intent.EXTRA_STREAM, outputFileUri);
sharePic.putExtra(Intent.EXTRA_SUBJECT, "Check This Out!");
sharePic.putExtra(Intent.EXTRA_TEXT,
"I did this on my Sketchify App!");
startActivity(Intent.createChooser(sharePic, "Send Email"));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
sketchit.setEnabled(true);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
screenHeight = metrics.heightPixels;
screenWidth = metrics.widthPixels;
location = Environment.getExternalStorageDirectory()
+ "/sketch.png";
back = Camera_Helpers.processImage(location, screenHeight,
screenWidth);
taken = true;
sketchit.setEnabled(taken);
shareit.setEnabled(taken);
image.setImageBitmap(back);
}
}
back is the modified bitmap i am trying to eventually attach to the email
Thanks!!!
Create Folder Directory and Save image into it: create directory where you want to save your images. Suppose the folder name is ImageFolder.
String location = Environment.getExternalStorageDirectory() + "/ImageFolder/";
//Creating Folder Directory
File imageDir = new File(location);
dir.mkdirs();
//Creating Image file
String imageName = "sketch.png";
File imageFile = new File(imageDir, imageName);
//If image file already exists then delete it.
if (imageFile.exists()) {
imageFile.delete();
}
//Writing the image to SDCard
try {
FileOutputStream out = new FileOutputStream(imageFile);
back.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources