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 ();
}
Related
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 created a folder in SDcard and also retrieve image from gallery to imageview. I want to save this imageview file image in to my external sdcard folder Multimedia/Images
private void showFileChooser() {
Intent ginetnt = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(ginetnt,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imgView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
And this is coding for create Folder SdCard
public void onStart(){
super.onStart();
String folder_main = "Multimedia";
File Mul= new File (Environment.getExternalStorageDirectory(), folder_main);
if(!Mul.exists()) {
if(!Mul.mkdir()){
Toast.makeText(this, Mul + " can't be created.", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, Mul+" can be created.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, Mul+" already exits.", Toast.LENGTH_SHORT).show();
}
File Images= new File (Environment.getExternalStorageDirectory() +"/" +folder_main, "Images");
if(!Images.exists()) {
if(!Images.mkdir()) {
Images.mkdirs();
}
}
File Audio= new File (Environment.getExternalStorageDirectory() +"/" +folder_main, "Audio");
if(!Audio.exists()) {
if(!Audio.mkdir()) {
Audio.mkdirs();
}
}
File Video= new File (Environment.getExternalStorageDirectory() +"/" +folder_main, "Video");
if(!Video.exists()) {
if(!Video.mkdir()) {
Video.mkdirs();
}
}
}
First extract the Bitmap from your ImageView.
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
Then you can save to your gallery with the below method.
public void saveBitmap(Bitmap bitmap) {
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/YourAlbum";
File dir = new File(file_path);
if (!dir.exists())
dir.mkdirs();//create a file to write bitmap data
File f = new File(dir, "yourImageName" + ".png");
try {
f.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
}
I used this piece of code to get the image from the gallery and then crop the image before saving it. Its running up and nicely for android built in gallery but giving NullPointerException in onActivityResult method where we get extras.getParcelable("data") on using google photos app on android. Any help would be appreciated. Thanks in advance :D
//This is called in oncreate() on clicking the upload from gallery button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK , android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
galleryIntent.putExtra("crop", "true");
startActivityForResult(galleryIntent,PICK_FROM_FILE);
//This is called on onActivityResult() method
if (requestCode == PICK_FROM_FILE && data != null) {
Bundle extras = data.getExtras();
//get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
//do whatever with thePic
}
It worked for me.
//This is my onActivityResult method.
if (resultCode == RESULT_OK && data != null) {
final Uri selectedImage = data.getData();
String root = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
File createDir = new File(root + "AppName" + File.separator);
if (!createDir.exists()) {
createDir.mkdirs();
}
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyhhmmss");
String format = s.format(new Date());
File file = new File(root + "AppName" + File.separator + format);
if (!file.exists()) {
try {
file.createNewFile();
copyFile(new File(getRealPathFromURI(selectedImage)), file);
} catch (IOException e) {
e.printStackTrace();
}
}
String filePath = file.GetAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(filepath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
int height = bitmap.getHeight();
int width = bitmap.getWidth();
Bitmap bmp = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
mImageView.setImageBitmap(bmp);
}
And this is the copyFile method that i have used in this.
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
Hope it works for you as well :D
I am building an Android app that takes photos, then uploads them to a Rails API.
The api expects the base64 encoded raw file bytes, to be stored as a temp file representing the image in JPG format.
However, the API is rejecting the uploaded file with this error message:
<Paperclip::Errors::NotIdentifiedByImageMagickError:
This seems to be due to a failure of encoding on the part of the Android app.
The base64 image bytes that I'm sending up look like this:
Which appears invalid just by looking at it.
The image is created in android by taking a pic with the Camera API and base64 encoding the resulting byteArray:
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Anyone know what I'm doing wrong here?
On button click for capturing an image from a camera use this
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
((Activity) context).startActivityForResult(intent, Constants.REQUEST_IMAGE_CAPTURE);
and on activityResult of the activity implement the following code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final ImageView uploadArea = (ImageView) attachmentDialog.findViewById(R.id.uploadArea);
Bitmap bitmap;
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] attachmentBytes = byteArrayOutputStream.toByteArray();
String attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);
uploadArea.setImageBitmap(rotatedBitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "CTSTemp" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I hope this will help you, and for any farther info, please ask
this is my code:
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (reqCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resCode == RESULT_OK) {
if (data.getData() == null) {
Bitmap bm = (Bitmap)
data.getExtras().get("data");
productImageImgView.setImageBitmap(bm);
productImageImgView.setVisibility(View.VISIBLE);
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss").format(new Date());
File pictureFile = new File(Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp + ".png");
try {
FileOutputStream fos = new FileOutputStream(
pictureFile);
bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
// String filePath = pictureFile.getAbsolutePath();
imageUri = Uri.fromFile(pictureFile);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
} else {
Bitmap photo = (Bitmap) data.getExtras().get("data");
productImageImgView.setImageBitmap(photo);
productImageImgView.setVisibility(View.VISIBLE);
imageUri = data.getData();
}
}
after saving image loses quality. i want to save Bitmap image with high quality or save image after improving quality.i need advice about this topic