Picasso Image Caching using Bitmap - java

This contents of this loadImage method never gets called although I am calling this method in OnActivityResult.
public void loadImage(Uri uri){
File file = new File(getApplicationContext().getExternalCacheDir().getAbsolutePath() + "/" +uid + ".jpg");
Log.d("Check Bitmap", "file" + file);
try {
Picasso picasso = Picasso.get();
Bitmap bitmap = picasso.load(uri).get();
Log.d("Check Bitmap", "bitmap working");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
} catch (Exception e) {
Log.d("Check Bitmap", "bitmap not working, cached");
e.printStackTrace();
}
My aim is to retrieve the image from the file.
This is my OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==1000){
{
if(resultCode == Activity.RESULT_OK){
imageUri = data.getData();
Context context;
final ProgressDialog dialog = new ProgressDialog(myProfile.this);
dialog.setMessage("Uploading Image...");
dialog.show();
profilepic.setImageURI(imageUri);
ref.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final Picasso picasso = Picasso.get();
picasso.setIndicatorsEnabled(true);
picasso.load(uri).into(profilepic);
downloadUri = uri;
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Image Uploaded!", Toast.LENGTH_SHORT).show();
loadImage(uri); //Here I call

You should not use space separated TAG for logs. Try replacing your "Check Bitmap" with something of one word (eg. "Checkere"). Then you will be able to see your Log in your Logcat.
You need to put everything inside a thread.
Here is the complete block of code for loadImage
public void loadImage(final Uri uri){
Thread thread = new Thread() {
#Override
public void run() {
Log.d("Checkere", "stuck at file");
File file = new File(getCacheDir() + File.separator + uid + ".jpg");
Log.d("Checkere", "file" + file);
try {
Picasso picasso = Picasso.get();
Bitmap bitmap = picasso.load(uri).get();
Log.d("Checkere", "bitmap working");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
Log.d("Checkere", e.getMessage());
e.printStackTrace();
}
}};
thread.start();
}
Note that I have also added these two lines in your code.
fOut.flush();
fOut.close();
I hope this helps!

Related

Uploading and retrieving image android studio Parse sever

I'm trying to pick multiple images from users gallery and upload (parse server) this images to parse object then retrieve it and set it in an image view
and also i need to pick one image from gallery and save to the users profile
what i have already tried:
//Before OnCreate
String da = "13412412412412414124ASDASDASDASDAD";
////After OnCreate
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final Uri imageUri = data.getData();
final InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
String encodedImage = encodeImage(selectedImage);
da=encodedImage;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private String encodeImage(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
private void ChooseImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
}
private void CreateThing() {
ParseObject thing = new ParseObject("Things");
thing.put("Image",da);
thing.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e==null)
Toast.makeText(class.this, "Done", Toast.LENGTH_SHORT).show();
else
Toast.makeText(class.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

Call a Share button Image from another class onCreate method and onActivityResult android

My first question would be, Is onCreate method needed on every new class in android ?
Next, can we use multiple onActivityResult method without causing distortion
?
For exemple my MainActivity and ShareActivity class both have their own onActivityResult and Oncreate method (code taken from git)
MainActivity is for opening camera and gallery
ShareActivity is for sharing images captured
Note : Both class check for permission first
I wanna call the ShareActivity in my MainActivity, the logical thing to do would be
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, ShareActivity.class);
startActivity(myIntent);
}
});
But my ShareActivity also has this
#OnClick(R.id.open_share)
void onShareTouched() {
boolean has_perms = EasyPermissions.hasPermissions(ShareActivity.this, perms);
if (has_perms) {
shareImageFromBitmap(this.bmp);
} else {
EasyPermissions.requestPermissions(
ShareActivity.this,
getString(R.string.rationale_storage),
SHARE_STORAGE_PERMS_REQUEST_CODE,
perms);
}
}
And then I thought about calling it like this
ShareActivity.getInstance().onShareTouched();
But the app keep crashing, everytime I call the Share class,
Edit : Should I use implement ?
Note :the Share class works fine without MainActivity (I tried in new project)
for better understanding I leave the complete code below
ShareActivity
public class ShareActivity extends AppCompatActivity {
private static ShareActivity instance;
private static final String TAG = "ShareActivity";
private final int SHARE_STORAGE_PERMS_REQUEST_CODE = 900;
private final int RESULT_LOAD_IMG_REQUEST_CODE = 778;
private final String[] perms = { android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE};
private static final String IMAGE_URL = null;
private Bitmap bmp;
#BindView(R.id.open_share)
SimpleDraweeView imageView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
bmp = getBitmapFromUrl(IMAGE_URL);
imageView2.setImageURI(Uri.parse(IMAGE_URL));
instance = this;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMG_REQUEST_CODE && resultCode == RESULT_OK) {
List<Image> images = ImagePicker.getImages(data);
if(images.size() > 0) {
String imagePath = images.get(0).getPath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagePath, options);
imageView2.setImageURI(Uri.fromFile(new File(imagePath)));
}
}
}
#OnClick(R.id.open_share)
void onShareTouched() {
boolean has_perms = EasyPermissions.hasPermissions(ShareActivity.this, perms);
if (has_perms) {
shareImageFromBitmap(this.bmp);
} else {
EasyPermissions.requestPermissions(
ShareActivity.this,
getString(R.string.rationale_storage),
SHARE_STORAGE_PERMS_REQUEST_CODE,
perms);
}
}
#AfterPermissionGranted(SHARE_STORAGE_PERMS_REQUEST_CODE)
private void shareImageFromBitmap(Bitmap bmp) {
Uri uri = getUriImageFromBitmap(bmp, ShareActivity.this);
if(uri == null) {
//Show no URI message
return;
}
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, IMAGE_URL);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/png");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
private Bitmap getBitmapFromUrl(String url) {
Uri uri = Uri.parse(url);
ImageRequest downloadRequest = ImageRequest.fromUri(uri);
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(downloadRequest, ShareActivity.this);
if (ImagePipelineFactory.getInstance().getMainFileCache().hasKey(cacheKey)) {
BinaryResource resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey);
byte[] data = null;
try {
data = resource.read();
} catch (IOException e) {
e.printStackTrace();
}
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
return null;
}
private Uri getUriImageFromBitmap(Bitmap bmp, Context context) {
if(bmp == null)
return null;
Uri bmpUri = null;
try {
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "IMG_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
bmpUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public static ShareActivity getInstance() {
return instance;
}
}
MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
if (requestCode == OPEN_THING) {
Uri uri = Objects.requireNonNull(data.getExtras()).getParcelable(ScanConstants.SCANNED_RESULT);
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
if (uri != null) {
getContentResolver().delete(uri, null, null);
}
scannedImageView.setImageBitmap(bitmap);
FileOutputStream outputStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/Scan Documents");
directory.mkdir();
String filename = String.format("d.jpg", System.currentTimeMillis());
File outFile = new File(directory, filename);
Toast.makeText(this, "Image Saved Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outFile));
sendBroadcast(intent);
try {
outputStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I found a better easier way
I had to completely change my method, I put everything in my button onClick
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable myDrawable = scannedImageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
try{
File file = new File(MainActivity.this.getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share Image Via"));
}catch (FileNotFoundException e){
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
});
No need ShareActivity it works great

Error to save image in gallery in Android Studio

public class MainActivity extends Activity {
ImageButton b1, b2;
ImageView v1;
private static int RESULT_LOAD_IMAGE = 1;
BitmapDrawable drawable;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.card);
b2 = findViewById(R.id.save);
v1 = findViewById(R.id.imageview1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawable = (BitmapDrawable) v1.getDrawable();
bitmap = drawable.getBitmap();
FileOutputStream outputStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "YourFolderName");
directory.mkdir();
#SuppressLint("DefaultLocale") String filename = String.format("%d.jpg",System.currentTimeMillis());
File outFile = new File(directory,filename);
try {
outputStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outFile));
sendBroadcast(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
ImageView imageView = findViewById(R.id.imageview1);
try {
Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
imageView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
}
public static void saveFrameLayout(FrameLayout frameLayout, String path) {
frameLayout.setDrawingCacheEnabled(true);
frameLayout.buildDrawingCache();
Bitmap cache = frameLayout.getDrawingCache();
try {
FileOutputStream fileOutputStream = new FileOutputStream(path);
cache.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
// TODO: handle exception
} finally {
frameLayout.destroyDrawingCache();
}
}
}
I want to save the image in the gallery. It is running but it is showing error on the run time.
Here I am picking the Image from the gallery and want to save that image again in the gallery. Already given the different path to save that picked image.
It is showing
"W/System.err: at >android.app.ActivityThread.main(ActivityThread.java:6692)" while I run the >code.
I already done entry in manifest file.
Your file (or the directory to said file) doesn't exist, you'll need to create the file using createNewFile, something along the following lines should work,
File outFile = new File(directory,filename);
//The below line shouldn't be required since you do directory.mkdir()
//file.getParentFile().mkdirs(); // Will create parent directories if not exists
file.createNewFile(); // Will create file if it doesn't exist
try {
//Rest of your code

setting image uri gives Unable to decode stream: java.io.FileNotFoundException:

I've simple app for capturing image using Camera using following code
#AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
Log.d(TAG, "launchCamera");
// Check that we have permission to read images from external storage.
String perm = android.Manifest.permission.READ_EXTERNAL_STORAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !EasyPermissions.hasPermissions(this, perm)) {
EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage),
RC_STORAGE_PERMS, perm);
return;
}
// Create intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Choose file storage location
File file = new File(Environment.getExternalStorageDirectory(), UUID.randomUUID().toString() + ".jpg");
mFileUri = Uri.fromFile(file);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// Launch intent
startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}
now I want to upload that image to Firebase storage
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_TAKE_PICTURE) {
if (resultCode == RESULT_OK) {
if (mFileUri != null) {
uploadFromUri(mFileUri);
} else {
Log.w(TAG, "File URI is null");
}
} else {
Toast.makeText(this, "Taking picture failed.", Toast.LENGTH_SHORT).show();
}
}
}
private void uploadFromUri(Uri fileUri) {
Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());
// [START get_child_ref]
// Get a reference to store file at photos/<FILENAME>.jpg
final StorageReference photoRef = mStorageRef.child("photos")
.child(fileUri.getLastPathSegment());
// [END get_child_ref]
// Upload file to Firebase Storage
// [START_EXCLUDE]
showProgressDialog();
// [END_EXCLUDE]
Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
photoRef.putFile(fileUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Upload succeeded
Log.d(TAG, "uploadFromUri:onSuccess");
// Get the public download URL
mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
Log.w("IMAGE_URL", "Path is " + mDownloadUrl.toString());
uploadedImage = (ImageView) findViewById(R.id.uploaded_img);
try{// Here I'm setting image in ImageView
uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
System.out.print(e.getCause());
}
// [START_EXCLUDE]
hideProgressDialog();
///updateUI(mAuth.getCurrentUser());
// [END_EXCLUDE]
}
})
);
}
in uploadFromUri() at line
try{// Here I'm setting image in ImageView
uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
System.out.print(e.getCause());
}
image is not set in ImageView and I get error
07-29 09:54:23.055 18445-18445/? W/IMAGE_URL: Path is https://firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6
07-29 09:54:23.056 18445-18445/? E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: https:/firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6: open failed: ENOENT (No such file or directory)
and if I open this link I see image there, question is why it is not set in image view
setImageURI() is for content URIs particular to the Android
platform, not URIs specifying Internet resources.
Try getting your bitmap from internet in a new thread an then add it to your ImageView. Like this:
uploadedImage.setImageBitmap(getImageBitmap(mDownloadUrl));
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
You also can use a useful library to set image (Internal and external images) called Picasso http://square.github.io/picasso/
Add Picasso library for image loading and use the following code.
Picasso.with(activity).load(imageURL)
.resize(imageWidth,imageHeight)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
Log.d(TAG,"successfully load the image");
}
#Override
public void onError() {
Log.d(TAG,"fail to load the image");
}
});

Change an image that is store in parse through android

I am trying to update an image that is saved in parse through the android app, I am able o retrieve it and load it to the app but I am not able to save the new image that I selected to replace the old one. This is how I tried to do it and it only saves the file on the current state and not to parse. This is the code that I have currently and it is not working the way I want it to. Kindly assist.
Code is as follows
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
Uri pickedImage = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(pickedImage);
Bitmap selectedImages = BitmapFactory.decodeStream(inputStream);
imageSelected.setImageBitmap(selectedImages);
selectedImages = ((BitmapDrawable) imageSelected.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImages.compress(Bitmap.CompressFormat.PNG, 5, stream);
byte[] imageRec = stream.toByteArray();
file = new ParseFile("profileUpdate.png", imageRec);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (null == e)
currentUser.put("ProfilePicture", file);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Unable to load image",
Toast.LENGTH_LONG).show();
}
}
}
}
I just added the currentUser.saveInBackground(); line after currentUser.put("ProfilePicture", file); and added a currentUser.remove("ProfilePicture"); before it and it worked.

Categories