Image compressing Android - java

I have created this app based on tutorials, ATM it successfully open the camera and displays it as imgOriginal on the screen. When i press the compress button I get a error relating to '.compressToFile(imageBitmap);
Error Message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.photocompressor, PID: 11123
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getName()' on a null object reference
at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)
at com.example.photocompressor.MainActivity$3.onClick(MainActivity.java:149)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if (resultCode == RESULT_OK) {
// if (resultCode == RESULT_IMAGE && resultCode == RESULT_OK ) {
if (resultCode == RESULT_OK && resultCode != RESULT_IMAGE) {
btnCompress.setVisibility(View.VISIBLE);
final Uri imageUri = data.getData();
try {
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imgOriginal.setImageBitmap(selectedImage);
////originalImage = new File(imageUri.getEncodedPath().replace("raw/", ""));
long size = DocumentFile.fromSingleUri(this, imageUri).length();
//txtOriginal.setText("Size: " + Formatter.formatShortFileSize(this, originalImage.length()));
txtOriginal.setText("Size: " + Formatter.formatShortFileSize(this, size));
Toast.makeText(MainActivity.this, "Size: " + size, Toast.LENGTH_LONG).show();
//Toast.makeText(MainActivity.this, "Size: " + Formatter.formatShortFileSize(this, originalImage.length()), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Something went Wrong", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
// }
Below is the compress button, error appears in '.compressToFile'. I would ideally like to have the option to replace the original file or to save as a new file, but havent even got the replace file to work yet.
btnCompress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int quality = seekBar.getProgress();
int width = Integer.parseInt(txtWidth.getText().toString());
int height = Integer.parseInt(txtHeight.getText().toString());
Toast.makeText(MainActivity.this, "Quality " + quality, Toast.LENGTH_SHORT).show();
try {
compressedImage = new Compressor(MainActivity.this)
.setMaxWidth(width)
.setMaxHeight(height)
.setQuality(quality)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(filepath)
//.compressToFile(originalImage);
.compressToFile(imageBitmap);
File finalFile = new File(filepath, originalImage.getName());
Bitmap finalBitmap = BitmapFactory.decodeFile(finalFile.getAbsolutePath());
imgCompressed.setImageBitmap(finalBitmap);
//long newsize = DocumentFile.fromSingleUri(this, image);
//txtCompressed.setText("size: " + Formatter.formatShortFileSize(MainActivity.this,newsize));
//Toast.makeText(MainActivity.this, filepath + " Something went Wrong", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error while Compressing", Toast.LENGTH_SHORT).show();
}
}
});

Related

Saving path to image

There is a function, adding user image to my app, but I need image to use again, so I chose SQLite Database to save path to image, my database works correctly. So in OnClick method, app show DialogWindow, where user choose image from gallery:
choosePath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//Type - image:
photoPickerIntent.setType("image/*");
//Start activity, waiting for result
startActivityForResult(photoPickerIntent, Pick_image);
}
});
Then onActivityResult is called:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode){
case Pick_image:
if(requestCode == RESULT_OK){
try {
final Uri imageUri = imageReturnedIntent.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
Log.e("mLog", "onActivityResult: " + imageStream + " " + imageReturnedIntent + " " + imageUri);
pathToImage = imageUri.toString();
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
}
But when I save path in SQlite:
ContentValues cv = new ContentValues();
cv.put("description", description);
cv.put("image_link", pathToImage);
cv.put("category", category[0]);
long res = mDb.insert("favourites", null, cv);
if (res > -1) {
Toast.makeText(getApplicationContext(), "Шаблон добавлен в любимые", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Ошибка", Toast.LENGTH_SHORT).show();
}
I get exception:
E/SQLiteDatabase: Error inserting description=dog image_link=null category=
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: favourites.image_link (code 1299 SQLITE_CONSTRAINT_NOTNULL)
I used debugger, but it didnt help me.
Please help me to solve this problem!
Correct your if condition, that causes your code not running inside if condition and getting pathToImage object null
// you are matching here request code with result status
if(requestCode == RESULT_OK)
//It should be
if(resultCode == RESULT_OK)

I want to upload multiple images to the server using multipart using volley android studio

I want to send multiple images using multipart volley in this format. the format that i have written below is in swift language:
multipartFormData.append(imageData, withName: "nverness\(i).jpg", fileName: "Inverness\(i).jpg" , mimeType: "image/jpeg")
I'm getting multiple images from gallery and save in list. This is done from my side and working perfectly. I want to send this list of images on server using the format that i have written above.
My code is here:
pickImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
return;
}
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
intent.setType("image/*");
startActivityForResult(intent,1);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1){
bitmaps = new ArrayList<>();
ClipData clipData = data.getClipData();
if (clipData != null){
for (int i =0 ; i < clipData.getItemCount() ; i++){
Uri imageUri = clipData.getItemAt(i).getUri();
try {
InputStream is = getContext().getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
bitmaps.add(bitmap);
Toast.makeText(getContext(), "Images successfully added", Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e){
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
}else {
Uri imageUri = data.getData();
try {
InputStream is = getContext().getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
bitmaps.add(bitmap);
Toast.makeText(getContext(), "Images successfully added here", Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e){
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}
how can i send this list to the server using volley android?

Operation finished with HTTP status code 409 (fail)

Hello There I am working on Next Cloud Api, and I am trying to upload an Image from my device as:
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
and the on activity result is as:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
try {
// Get the Uri of the selected file
Uri uri = data.getData();
// Get the path
String path = getPath(MainActivity.this, uri);
File fi = new File(path);
//set the image to image view
iv.setImageURI(Uri.fromFile(fi));
Date lastModDate = new Date(fi.lastModified());
startUpload(fi, "/testfolder", getMimeType2(Uri.fromFile(fi)),lastModDate.toString());
Log.e(TAG, "file " + fi.toString() + " remote path " + mServerUri + " mime " + getMimeType2(Uri.fromFile(fi))+" date "+lastModDate.toString());
} catch (Exception e) {
Log.e(TAG, "eee " + e.toString());
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {"_data"};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Though I just created a new folder using the api documentation and it works well good and created a folder! Although every this is working in good condition like reading a file from Next Cloud too!
The problem is with the image upload from the device! I am getting the following error while I am trying to upload:
Operation finished with HTTP status code 409 (fail)
I currently have no idea what I have been doing wrong, can somebody please give some idea about what is being done wrong!
HTTP Error 409 means that there is a confict with the resource on the server.
You should check the response from the server to understand how to resolve the confict.
More info: https://httpstatuses.com/409

android camera takePicture goes wrong

logcat message remind:
failure delivering result ResultInfo{who = null,request=131073,result=-1,date=null}
fatal exception at com.example.newpingziyi.FindFragment.doPhoto(FindFragment.java:178);
178lines:
Cursor cursor = getActivity().managedQuery(photoUri, pojo, null, null,
null);
onActivityResult after photos pick up
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
doPhoto(requestCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void doPhoto(int requestCode, Intent data) {
if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
if (data == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
photoUri = data.getData();
if (photoUri == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
}
String[] pojo = { MediaColumns.DATA };
// fatal exception
Cursor cursor = getActivity().managedQuery(photoUri, pojo, null, null,
null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
try {
if (Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
} catch (Exception e) {
Log.e(TAG, "error:" + e);
}
}
Log.i(TAG, "imagePath = " + picPath);
if (picPath != null) {
Intent startEx = new Intent(getActivity(), PhotoPre.class);
startEx.putExtra(SAVED_IMAGE_DIR_PATH, picPath);
startActivity(startEx);
} else {
Toast.makeText(getActivity(), R.string.photo_err, Toast.LENGTH_LONG)
.show();
}
}
use this
cursor.moveToLast();
instead of cursor.moveToFirst();

Android - Cropping after Camera and Gallery Intents Gives Strange Results

I'm trying to launch an Android camera intent and a choose-photo intent (two buttons, one for take photo, one for choose from gallery) and both need a crop intent launched after them then have the cropped photo returned to my app's activity. I've gone through a bunch of the examples posted elsewhere, but I'm getting strange reults with my implementation.
For the take photo event, it appears to work fine, except after taking a photo and going into crop mode, the wrong photo pops up. Instead of cropping the photo you just took it crops an older photo and I can't figure out where it's coming from. Also, sometimes after finishing the crop intent, it crashes with a nullpointerexception after Parcel.readException (can't always reproduce, but I think it haappens more if you take a picture and crop as quickly as possible).
For the choose photo intent, your gallery pops up as expected but upon choosing a photo all that happens is the message "Saved" is toasted instead of returning to my app's activity with the image. I believe I have a misunderstanding of how the choose photo intent works (I pretty much reused the code for the take photo intent).
In both cases, in crop mode you are still allowed to resize the cropped area despite having specified "scale" = false.
My code is as follows:
public class TestPhotoActivity extends Activity {
private ImageView imageView;
private Uri imageUri;
private int int_Height_crop = 600;
private int int_Width_crop = 600;
public final static int TAKE_PICTURE = 0;
public final static int CHOOSE_PICTURE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_photo);
imageView = (ImageView) findViewById(R.id.photo);
Button take_photo = (Button) findViewById(R.id.take_photo);
take_photo.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
takePhoto(view);
}
});
Button choose_photo = (Button) findViewById(R.id.choose_photo);
choose_photo.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
choosePhoto(view);
}
});
}
public void takePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE", null);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", int_Width_crop);
intent.putExtra("outputY", int_Height_crop);
intent.putExtra("scale", false);
intent.putExtra("return-data", true);
File photo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, TAKE_PICTURE);
}
public void choosePhoto(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", int_Width_crop);
intent.putExtra("outputY", int_Height_crop);
intent.putExtra("scale", false);
intent.putExtra("return-data", true);
File photo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(intent, CHOOSE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
Log.d("photo", "requestCode: " + requestCode + "resultCode: " + resultCode + "wanted result: " + Activity.RESULT_OK);
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
Log.w("photo", "Null data, but RESULT_OK, from image picker!");
Toast t = Toast.makeText(this, "No photo picked.", Toast.LENGTH_SHORT);
t.show();
return;
}
final Bundle extras = data.getExtras();
if (extras != null) {
Log.d("photo", "extras is not null");
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
Log.d("photo", "data.getAction() is not null. setting image.");
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.e("photo", e.toString());
}
}
}
case CHOOSE_PICTURE:
Log.d("photo", "requestCode: " + requestCode + "resultCode: " + resultCode + "wanted result: " + Activity.RESULT_OK);
if(resultCode == RESULT_OK){
Log.d("photo", "resultCode is ok");
if (data == null) {
Log.w("photo", "Null data, but RESULT_OK, from image picker!");
Toast t = Toast.makeText(this, "No photo picked.", Toast.LENGTH_SHORT);
t.show();
return;
}
final Bundle extras = data.getExtras();
if (extras != null) {
Log.d("photo", "extras is not null");
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
Log.d("photo", "data.getAction() is not null. setting image.");
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.e("photo", e.toString());
}
}
}
}
}
}
Any help is greatly appreciated!
EDIT: I should also note that I'm testing on an LG Optimus LTE, Android 2.3
I think your problem comes from useing System.currentTimeMillis() in the temp file name. This would explain sometimes getting an older file.
I would suggest just reusing the same temp file.
Hope it helps...

Categories

Resources