Couldn't upload a picture using google photos - android

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

Related

Copy image from one folder to another - Android

Hi Everyone I am trying to copy an image from one folder to another which user selects from the gallery. It's not throwing any error as well. Please check the below code.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName = "";
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY) {
try {
Uri selectedImageUri = data.getData();
String path = getPathFromURI(selectedImageUri);
switch (cameraNo) {
case 1:
Bitmap bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
imageBtn1.setImageBitmap(bitmap1);
reduceImageSize(path);
fileName = path.substring(path.lastIndexOf("/")+1);
try {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
String destinationImagePath= "/MyImages/file.jpg";
File source= new File(path);
File destination= new File(sd, destinationImagePath);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
}
imageArrayList.add(path);
imageNameList.add(fileName);
break;
}}
this is working for me, give it a try ;):
public static void copyFile(String inputPath, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(inputPath);
out = new FileOutputStream(outputPath);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file (You have now copied the file)
out.flush();
out.close();
out = null;
LOGGER.debug("Copied file to " + outputPath);
} catch (FileNotFoundException fnfe1) {
LOGGER.error(fnfe1.getMessage());
} catch (Exception e) {
LOGGER.error("tag", e.getMessage());
}
}
if you have a source path and destination path then try this one
/**
* copy contents from source file to destination file
*
* #param sourceFilePath Source file path address
* #param destinationFilePath Destination file path address
*/
private void copyFile(File sourceFilePath, File destinationFilePath) {
try{
if (!sourceFilePath.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFilePath).getChannel();
destination = new FileOutputStream(destinationFilePath).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
All the best

ThumbnailUtils.createVideoThumbnail not working for nougat device

Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(localUrl,
MediaStore.Video.Thumbnails.MINI_KIND);
Here bitmap gives me null value.
The exact same condition I have faced, Only it was unable to create video thumbnail in higher version or high rated device. You are getting path of video in OnActivityResult something like this.
if (requestCode == 3 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
String mimeType = getActivity().getContentResolver().getType(uri);
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
Log.e("PICTURE PATH", picturePath);
File file = new File(picturePath);
long length = file.length();
length = length / 1024;
long length2 = length / 1024;
if (length2 > 25) {
Toast.makeText(getActivity(), "You cannot upload file more than 25 MB", Toast.LENGTH_SHORT).show();
} else {
if (mimeType.contains("image")) {
Log.e("mimeType", mimeType);
Log.e("gif", picturePath);
Intent intent = new Intent(getActivity(), UploadImagePostActivity.class);
intent.putExtra("DESTINATION", picturePath);
startActivity(intent);
getActivity().finish();
} else if (mimeType.contains("video")) {
Log.e("mimeType", mimeType);
Log.e("Video path", picturePath);
Intent intent = new Intent(getActivity(), UploadVideoPostActivity.class);
intent.putExtra("VIDEO_DESTINATION", picturePath);
startActivity(intent);
getActivity().finish();
}
}
}
Now you will get the path of video and you have to make video thumbnail after getting video path. sometime it may raise the problem of not getting correct path because some devices have different path hierarchy. so you have to save your thumbnail at a particular position and retrieve it back. code is give below.
// type 2 for video
File uri = new File(filePath);
//create thumbnail image
thumb = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Video.Thumbnails.MINI_KIND);
img_tumbnail.setImageBitmap(thumb);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
thumbNailfile = savebitmap(thumb);
Log.e("Thumbnail path", "" + thumbNailfile);
} catch (IOException e) {
e.printStackTrace();
}
}
});
and the saving thumbnail file at specific path. now it will return the correct path of file.
// save bitmap into internal memory
public static File savebitmap(Bitmap bmp) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp = ((BitmapDrawable) img_tumbnail.getDrawable()).getBitmap();
bmp.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//
thumnailImagePath = Environment.getExternalStorageDirectory() + File.separator + "123.jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "123.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}

android compress image size before sending to server

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 ();
}

how to store and fetch clicked and gallery image into sqlite database?

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);

Android save Bitmap with high quality or improve Bitmap quality

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

Categories

Resources