I am attempting to upload an image from an android application to the server. I am calling the upload function and trying to get the image from ImageVeiw but no success. The image is set on the ImageVeiw from the gallery or camera.
Unable to get the file to send to the server
This is my code that I am using to set image from camera and gallery.
if(requestCode == CAMERA_REQUEST & resultCode == RESULT_OK){
Log.d("camera/gallery", "camera");
Bitmap photo = (Bitmap) data.getExtras().get("data");
profilePicture.setImageBitmap(photo);
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Log.d("camera/gallery", "gallery");
// get image from gallery
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);
// check orientation of image and rotate if required
ExifInterface exifInterface = null;
try{
File pictureFile = new File(picturePath);
exifInterface = new ExifInterface(pictureFile.getAbsolutePath());
} catch (IOException e){
e.printStackTrace();
}
int orientation = exifInterface.ORIENTATION_NORMAL;
if(exifInterface != null){
orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
switch(orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
loadedBitmap = rotateBitmap(loadedBitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
loadedBitmap = rotateBitmap(loadedBitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
loadedBitmap = rotateBitmap(loadedBitmap, 270);
break;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
loadedBitmap = flipBitmap(loadedBitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
loadedBitmap = flipBitmap(loadedBitmap, false, true);
default:
loadedBitmap = loadedBitmap;
}
// set image to ImageView
profilePicture.setImageBitmap(loadedBitmap);
}
I am able to get the bitmap image and trying to save it to the file. I am later trying to retrieve the same file and upload it to the server using retrofit
I am getting this error from retrofit on failure
W/System.err: java.io.FileNotFoundException: file:/data/user/0/com.example.fileuploaddemo/files/cleaton_profile_20191023T111341.png (No such file or directory)
Code for storing and retrieving the file and send the image file
public void uploadProfileImage(){
Uri fileUri = getSelectedFile();
if(Uri.EMPTY.equals(fileUri)){
Toast.makeText(this, "Exception Occurred", Toast.LENGTH_SHORT).show();
} else {
File originalFile = FileUtils.getFile(fileUri.toString());
Log.d(TAG, "in upload"+originalFile.getAbsolutePath());
RequestBody filePart = RequestBody.create(MediaType.parse("image/*"), originalFile);
MultipartBody.Part file = MultipartBody.Part.createFormData("upload", originalFile.getName(), filePart);
RequestBody modePart = RequestBody.create(MultipartBody.FORM, "profilepicture");
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
apiInterface.uploadPhoto(file, modePart).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Upload Fail", Toast.LENGTH_SHORT).show();
t.printStackTrace();
}
});
}
}
public Uri getSelectedFile(){
try{
String username = "cleaton";
// get bitmap from image set on imageview and convert to byte array
BitmapDrawable bitmapDrawable = (BitmapDrawable) profilePicture.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
byte[] bitmapdata = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
File file = new File(getFilesDir(), username+"_profile_"+timeStamp+".png");
// insert byte array into file output stream with name
FileOutputStream fileOutputStream = openFileOutput(username+"_profile_"+timeStamp+".png", MODE_PRIVATE);
fileOutputStream.write(bitmapdata);
fileOutputStream.flush();
fileOutputStream.close();
File profileImageFile = new File(file.getAbsolutePath());
Log.d(TAG, "file retrieve"+profileImageFile);
Uri fileUri = Uri.fromFile(profileImageFile);
Log.d(TAG, "file Uri"+fileUri);
return fileUri;
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
return null;
}
catch(IOException ioe){
ioe.printStackTrace();
return null;
}
}
To expound on Webfreak's answer:
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Once the Bitmap is retrieved, you can create a byte stream from which you can read the bytes and send those to your network socket by using a method similar to those below. Without knowing your upload method I am not sure if this is sufficient.
private InputStream getBitmapInputStream(BitmapFactory.Options options,
Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(getCompressionFormat(options), 100 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
return new ByteArrayInputStream(bitmapdata);
}
private Bitmap.CompressFormat getCompressionFormat(BitmapFactory.Options options) {
if (options == null || options.outMimeType == null) return Bitmap.CompressFormat.JPEG;
if (options.outMimeType.endsWith("/png")) {
return Bitmap.CompressFormat.PNG;
} else if (options.outMimeType.endsWith("/webp")) {
return Bitmap.CompressFormat.WEBP;
} else {
return Bitmap.CompressFormat.JPEG;
}
}
Fist you need to get the bitmap from Imageview:
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Once you have bitmap, you can upload it to server.
Related
I'm try to accomplish the following task:
Selecting an image from Gallery
Rotating the image (if necessary) to the right orientation using ExifInterface
Upload the image to Firebase
Question
If image requires rotation, i'll end up with a rotated Bitmap file. How do i convert this Bitmap file to an Uri so that i can upload to Firebase?
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == Activity.RESULT_OK) {
mImageUri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),mImageUri);
rotatedBitmap = rotateImageIfRequired(getContext(), bitmap, mImageUri);
mVideoImage.setImageBitmap(rotatedBitmap);
imageHeight = bitmap.getHeight();
imageWidth = bitmap.getWidth();
}catch (IOException e){
e.printStackTrace();
}
}
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {
InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
ei = new ExifInterface(input);
else
ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
To upload a bitmap into FireBase storage, you need to turn it into a byte array. You can do this by creating a ByteArrayOutputStream.
ByteArrayOutputStream boas = new ByteArrayOutputStream();
Then compress the bitmap into a format like JPEG or PNG. The compress method takes 3 parameters, the format, the quality, and the ByteArrayOutputStream.
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, boas);
Then create a reference to your FireBase Storage Reference, where you want to put the photo.
String imageFileName = "ExampleName";
StorageReference ref = FirebaseStorage.getInstance().getReference().child("images").child(imageFileName);
Here, I created a folder called 'images' and a file inside which is named using the previously created imageFileName String
Then I can upload it to FireBase using an UploadTask by saying
UploadTask task = ref.putBytes(data);
Using this task, you can create success and failure listeners.
task.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
In my Android App, I have an option where a user can take his photograph or upload an image from his Gallery at the time of registration. This image, once successfully taken by camera or selected from Gallery, is shown in an ImageView. Below is the onClick of ImageView code that starts this process.
This is from Activity Layout.
<ImageView
android:id="#+id/imgUserImage"
android:layout_width="150dp"
android:layout_height="150dp"
android:scaleType="centerCrop"
android:onClick="changePicture"
app:srcCompat="#drawable/profile_image_not_provided"
android:layout_below="#+id/textView2"
android:layout_alignParentEnd="true"
android:layout_marginTop="10dp" />
This is from Activity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imgProfilePicture = (ImageView)findViewById(R.id.imgUserImage);
int exif_orn_a;
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
imgProfilePicture.setImageURI(selectedImage);
imgProfilePicture.setImageBitmap(mphoto);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
else if (requestCode == PICK_IMAGE_GALLERY) {
Uri selectedImage = data.getData();
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Bitmap lphoto = null;
Cursor cur = this.getContentResolver().query(selectedImage, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
Toast.makeText(Register.this, "Picture Orientation "+orientation, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Register.this, "Wrong Orientation", Toast.LENGTH_LONG).show();
}
if (cur != null) cur.close();
try {
lphoto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imgProfilePicture.setImageURI(selectedImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
lphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have managed to get the Orientations properly. Now the problem is, how should I rotate the image before imgProfilePicture.setImageURI(selectedImage);.
I managed to find the solution. Please feel free to post a better solution, if you think this can be improvised.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imgProfilePicture = (ImageView)findViewById(R.id.imgUserImage);
int exif_orn_a;
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
imgProfilePicture.setImageURI(selectedImage);
imgProfilePicture.setImageBitmap(mphoto);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
else if (requestCode == PICK_IMAGE_GALLERY) {
Uri selectedImage = data.getData();
//Starting from here, I am checking the Orientation and storing the result in orientation variable.
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Bitmap lphoto = null;
Cursor cur = this.getContentResolver().query(selectedImage, orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
Toast.makeText(Register.this, "Picture Orientation "+orientation, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Register.this, "Wrong Orientation", Toast.LENGTH_LONG).show();
}
if (cur != null) cur.close();
//This is the end of Orientation Check.
try {
lphoto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imgProfilePicture.setImageURI(selectedImage);
//Based on the Orientation Check result, I rotate the ImageView Image to make it straight.
if (orientation == 270) {
imgProfilePicture.setRotation(-90);
} else if (orientation == 0) {
imgProfilePicture.setRotation(0);
}
//This is the end of Image Rotation based on the Orientation Check Result.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
lphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send in Bitmap form
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have tried multiple solutions from the internet with no luck, How do I go about changing the image size when I upload on app?
I want it to be in a way that when I upload a 2MB file,it gets sent to the server with size = 50kb.
Please help me
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//get image thumbnail
if (requestCode == REQUEST_CODE_PICKER && resultCode == RESULT_OK && data != null) {
ArrayList<Image> images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES);
absolutePath = null;
// do your logic ....
for (Image img : images) {
Log.v(LOG_TAG, img.getName() + " " + img.getPath());
absolutePath = img.getPath();
absolutePath = String.valueOf(Compressor.getDefault(getContext()).compressToFile(imageFile));
Bundle bundleExtras = data.getExtras();
image = (Bitmap) bundleExtras.get("data");
}
consultantProfileImageView.setImageBitmap(getBitmapFromPath(absolutePath));
new UploadConsultantProfileImageTask(getContext(), absolutePath).execute();
postConsultant();
}
}
public File getBitmapFromPath(String filePath) {
File imageFile = new File(filePath);
Bitmap imageBitmap = null;
imageBitmap = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream in = new ByteArrayInputStream(bos.toByteArray());
File compressedImageFile = Compressor.getDefault(getContext()).compressToFile(imageFile);
if (compressedImageFile.exists()) {
imageBitmap = BitmapFactory.decodeFile(compressedImageFile.getAbsolutePath());
}
return compressedImageFile;
}
Try using below it will compress the image to 80 percent. You can change the percentage of compression according to your requirement.
public File getBitmapFromPath(String filePath) {
File imageFile = new File(filePath);
OutputStream fout = new FileOutputStream(file);
Bitmap bitmap= BitmapFactory.decodeFile(filePath);
bitmap.compress(CompressFormat.JPEG, 80, fout);
fout.flush();
fout.close();
return imageFile;
}
Try
int compressionRatio = 2; //1 == originalImage, 2 = 50% compression, 4=25% compress
File file = new File (imageUrl);
try {
Bitmap bitmap = BitmapFactory.decodeFile (file.getPath ());
bitmap.compress (Bitmap.CompressFormat.JPEG, compressionRatio, new FileOutputStream (file));
}
catch (Throwable t) {
Log.e("ERROR", "Error compressing file." + t.toString ());
t.printStackTrace ();
}
i am not able to store the path and image into database, i want to store path or image into database and i want to fetch that image and set to imageview after updating profile..here is my onactvity result please help me.
#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);
ImagePaht = CommonUtility.encodeTobase64(bitmap);
mAddProfilePic.setImageBitmap(bitmap);
mAddProfilePic.setScaleType(ImageView.ScaleType.MATRIX);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
boolean delete = 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);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byteArray = stream.toByteArray();
outFile.flush();
outFile.close();
} catch (FileNotFoundException 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);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
// Log.e("path of ", picturePath + "");
ImagePaht = CommonUtility.encodeTobase64(thumbnail);
mAddProfilePic.setImageBitmap(thumbnail);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
mAddProfilePic.setScaleType(ImageView.ScaleType.MATRIX);
}
}
}
//this my method to save in database
private void saveInDbHospitalTable() {
Log.e("file name", "" + ImagePaht);
Table_Hospital_Methods mTable_Hospital_Methods = new Table_Hospital_Methods(getApplicationContext());
//String profilePictureURL = String.valueOf(byteArray);
// Log.e("profilePictureURL", "" + profilePictureURL);
String hospitalName = mHospitalName.getText().toString();
String doctorName = mDocName.getText().toString();
String registrationNo = mRegistrationNumber.getText().toString();
String hospitalPhoneNumber = mHospitalPhoneNumber.getText().toString();
String doctorPhoneNumber = mDoctorPhoneNumber.getText().toString();
String hospitalAddress = mHospiatlAddress.getText().toString();
ModelHospitalProfile modelHospitalProfile = new ModelHospitalProfile(byteArray, hospitalName,
doctorName, registrationNo, hospitalPhoneNumber, doctorPhoneNumber, hospitalAddress);
long hospitalId= mTable_Hospital_Methods.gethospitalId();
Log.e("hospitalId", "" + hospitalId);
if(mTable_Hospital_Methods.getHospitalCount()>0 && userName1==1) {
mTable_Hospital_Methods.updateToDo(modelHospitalProfile,hospitalId);
Log.e("update", "update");
}
else{
mTable_Hospital_Methods.insertHospital(modelHospitalProfile);}
}
For storing image into your database, you can either save image path or can save Base64 image into your database
Here, we are storing image path into database
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
settingImaePath(fileUri);
}
}
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
Log.i("file path", "" + filePath);
final Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
File imageFile = null;
String mPath = null;
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + now.getTime() + ".jpg";
imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
UserProfile userProfile = new UserProfile();
userProfile.setImagePath(mPath);
ProfileTable.getInstance().add(signupBean); // Here setting gallery image path into ProfileTable
userImage.setImageBitmap(bitmap); // userImage is an Imageview
} catch (IOException e) {
e.printStackTrace();
}
}
public void settingImaePath(Uri fileUri) {
String filePath = fileUri.getPath();
if (filePath != null) {
// Displaying the image or video on the screen
previewMedia(filePath);
}
}
private void previewMedia(String filePath) {
// Checking whether captured media is image or video
Log.i("file path", "" + filePath);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throw s OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
File imageFile = null;
String mPath = null;
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + now.getTime() + ".jpg";
imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 80;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
UserProfile userProfile = new UserProfile();
userProfile.setImagePath(mPath);
ProfileTable.getInstance().add(signupBean); // Here setting gallery image path into ProfileTable
userImage.setImageBitmap(bitmap);
}
//For Viewing save image from path
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
I have made a demo to make a pic with the cam, save the image, and then, in other activity show the last pic made it. This is OK with the emulator, but when I install my demo in a real phone, I can make the pic, but the file size saved is O KB.
//This is the method where I make the photo
private boolean makePhoto(){
try{
ImageCaptureCallback camDemo = null;
SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
String filenameTimeStamp = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, String.format("%s.jpg", filenameTimeStamp));
values.put(ImageColumns.DESCRIPTION, "Imagen desde Android Emulator");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
Log.d("titulo: ", values.get(MediaColumns.TITLE).toString());
camDemo = new ImageCaptureCallback(getContentResolver().openOutputStream(uri));
this.camera.takePicture(this.mShutterCallback, this.mPictureCallback, camDemo);
Log.d("makePhoto", "Foto hecha");
return true;
}catch(Exception ex){
ex.printStackTrace();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, ex.toString(), duration);
toast.show();
}
return false;
}
//This is the object where the pic taken is saved
public class ImageCaptureCallback implements PictureCallback {
private OutputStream fileoutputStream;
public ImageCaptureCallback(OutputStream fileoutputStream){
this.fileoutputStream = fileoutputStream;
}
public void onPictureTaken(byte[] data, Camera camera){
try{
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap myImage = BitmapFactory.decodeByteArray(data, 0, data.length,options);
BufferedOutputStream bos = new BufferedOutputStream(this.fileoutputStream);
myImage.compress(CompressFormat.JPEG, 75, bos);
bos.flush();
bos.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
What happened?
I am sending you the code for taking picture and take the picture into your application.
First of all add the below intend:
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile);
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(i, CAMERA_PIC_REQUEST);
And then add the below startActivityForResule in your code
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode)
{
case SELECT_PICTURE:
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
// file path of selected image
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
encode = Base64.encodeBytes(byteArray);
try {
byte[] decode = Base64.decode(encode);
Bitmap bmp = BitmapFactory.decodeByteArray(decode, 0,
decode.length);
imgview_photo.setImageBitmap(bmp);
btn_getphoto.setVisibility(View.INVISIBLE);
btn_cancel.setVisibility(View.VISIBLE);
btn_upload.setVisibility(View.VISIBLE);
}
catch (IOException e) {
e.printStackTrace();
}
break;
case CAMERA_PIC_REQUEST:
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath);
int width = bmp.getWidth();
int height = bmp.getHeight();
float scaleWidth = ((float) 300) / width;
float scaleHeight = ((float) 300) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, width,
height, matrix, true);
ByteArrayOutputStream baostream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, baostream);
byte[] byteArrays = baostream.toByteArray();
encode = Base64.encodeBytes(byteArrays);
try {
byte[] decode = Base64.decode(encode);
Bitmap bitmp = BitmapFactory.decodeByteArray(decode, 0,
decode.length);
imgview_photo.setImageBitmap(bitmp);
btn_getphoto.setVisibility(View.INVISIBLE);
btn_cancel.setVisibility(View.VISIBLE);
btn_upload.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
}