I saved an image using sharedpreferences in navigation header picture. But when I restart the app, it resets to the default picture. Can anyone help me plz?
I used intent to pass the image from MyProfile.java to MainActivity.class
Main Activity:
public void getIMG(){
if(getIntent().hasExtra("byteArray")) {
Bitmap _bitmap = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
imgProfile.setImageResource(R.mipmap.icon_round);
imgProfile.setImageBitmap(_bitmap);
imgProfile.buildDrawingCache();
Bitmap bitmap = imgProfile.getDrawingCache();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
_bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();
}
MyProfile(From where I received the image)
[public void setProfilePhoto(View view){
ImageView ivphoto = (ImageView)findViewById(R.id.userphoto);
//code image to string
ivphoto.buildDrawingCache();
Bitmap bitmap = ivphoto.getDrawingCache();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte\[\] image=stream.toByteArray();
//System.out.println("byte array:"+image);
//final String img_str = "data:image/png;base64,"+ Base64.encodeToString(image, 0);
//System.out.println("string:"+img_str);
String img_str = Base64.encodeToString(image, 0);
Intent _intent = new Intent(this, MainActivity.class);
_intent.putExtra("byteArray", image);
startActivity(_intent);
//decode string to image
String base=img_str;
byte\[\] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
ImageView ivsavedphoto = (ImageView)this.findViewById(R.id.usersavedphoto);
ivsavedphoto.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) );
//save in sharedpreferences
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("userphoto",img_str);
editor.commit();
}][1]
When you start the activity where you are showing the image use the following code to get the stored image from the shared preferences.
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
String savedImage=preferences.getString("userphoto","");
Now, convert your image string to bytes etc.
Hope this will help you!!
Related
I am developing and android blog application where I want to share my current blog page screenshot.I try but it showing file format is not supported..please help me to find my error..Thanks in advance
MyAdapter.java
sendImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap app_snap = ((BitmapDrawable)movie_image.getDrawable()).getBitmap();
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SaveImg";
System.out.println("****FILEPATH **** : " + file_path);
File imagePath = new File(Environment.getExternalStorageDirectory() + "/scr.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
System.out.println("****FILEPATH1 **** : " + file_path);
app_snap.compress(Bitmap.CompressFormat.PNG, 200, fos);
System.out.println("****FILEPATH2 **** : " + file_path);
fos.flush();
fos.close();
}
catch (IOException e) {
System.out.println("GREC****** "+ e.getMessage());
}
Intent sharingIntent = new Intent();
Uri imageUri = Uri.parse(imagePath.getAbsolutePath());
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
context.startActivity(sharingIntent);
}
});
Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:
First, you need to add a proper permission to save the file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
If you want to use this on fragment view then use:
View v1 = getActivity().getWindow().getDecorView().getRootView();
instead of
View v1 = getWindow().getDecorView().getRootView();
on takeScreenshot() function
Note:
This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:
Android Take Screenshot of Surface View Shows Black Screen
if u have any doubt please go through this link
You can get the Bitmap of your screen view inside your layouts. Where view will be your layout views like Linear or RelativeLayout
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap returnedBitmap = view.getDrawingCache();
then have to convert into byte[] so that you can send with the Intent like this following:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
and send data with Intent like this:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("bitmap_",byteArray);
get Intent on your SecondActivity like this:
byte[] byteArray = getIntent().getByteArrayExtra("bitmap_");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
I have finished the camera module for my text recognizer app, but the image quality is too low, the Text detector engine sometimes cant get any text from image. It still look good in preview, my phone is Pixel XL, so i think it not the camera problem. Maybe when i pass the image's bitmap to Text detector activity, it reduced the quality, how can i recover?
am using intent.putExtra to pass the bitmap, this is my code:
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Intent intent = new Intent(MainActivity.this, GetTextActivity.class);
intent.putExtra("key", data);
startActivity(intent);
}
};
and this is in the receiver:
byte[] byteArray = getIntent().getByteArrayExtra("key");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imgCaptured.setImageBitmap(bmp);
//text recognizer
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.w("MainActivity_capture", "Detector is not available");
} else {
Frame frame = new Frame.Builder().setBitmap(bmp).build();
SparseArray<TextBlock> items = textRecognizer.detect(frame);
StringBuilder sb = new StringBuilder();
for(int i=0;i<items.size();i++){
TextBlock item = items.valueAt(i);
sb.append(item.getValue());
sb.append("\n");
}
tvGetText.setText(sb);
}
I have a simple ImageView that when I click on it the camera appears and requests a photo, you take the photo and that ImageView turns into the photo, stuff like this:
Uri pictureUri;
ImageViewer pic = findViewById(...);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
try {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
String path=String.valueOf(data.getData());
pictureUri = Uri.fromFile(new File(path));
pic.setImageBitmap(thumbnail);
After the camera request the picture is loaded into the Imageviewer but and then I try to upload it to Firebase using:
StorageMetadata metadata = new StorageMetadata.Builder()
.setContentType(animal.getPictureID()+"/jpeg")
.build();
mStorageRef.child(animal.getPictureID()).putFile(pictureUri,metadata);
Where animal.getPictureID it's simply an ID given before. Now the issue here is that at the putFile() it keeps returning FileNotFoundException.
Also while we're at it if you know why the image in Imageviewer is in such low quality it would also be ncie but the main issue is really the Firebase storage.
You can get Bitmap from request by using:
InputStream stream = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
To store it to Firebase storage:
String path = "images/"+imgName;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// this will compress an image that the uplaod and download would be faster
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] data = baos.toByteArray();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageReference = storage.getReference();
StorageReference reference = storageReference.child(path);
UploadTask uploadTask = reference.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.i(TAG, "Image was saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Image wasn't saved. Exception: "+e.getMessage());
}
});
You can use the Base64 Android class:
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
You'll have to convert your image into a byte array though. Here's an example:
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
and decode the image when needed back
Main Activity
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = ((TextView) view.findViewById(R.id.recipe_title)).getText().toString();
String time = ((TextView) view.findViewById(R.id.time)).getText().toString();
String servings = ((TextView) view.findViewById(R.id.servings)).getText().toString();
String calories = ((TextView) view.findViewById(R.id.calories)).getText().toString();
ImageView thumbnail = (ImageView) view.findViewById(R.id.recipe_img);
Intent intent = new Intent(context, ActivityDetail.class);
intent.putExtra("RecipeTitle", title);
intent.putExtra("RecipeTotalTime", time);
intent.putExtra("RecipeServings", servings);
intent.putExtra("RecipeCalories", calories);
context.startActivity(intent);
}
});
Detail Activity
TextView time = (TextView)findViewById(R.id.time_detail);
TextView servings = (TextView)findViewById(R.id.servings_detail);
TextView calories = (TextView)findViewById(R.id.calories_detail);
ImageView thumbnail = (ImageView)findViewById(R.id.image_paralax);
time.setText(getIntent().getExtras().getString("RecipeTotalTime"));
servings.setText(getIntent().getExtras().getString("RecipeServings"));
calories.setText(getIntent().getExtras().getString("RecipeCalories"));
How can I send a thumbnail from the first Activity to second Activity. In the second `Activity, the thumbnail will be shown on an ImageView.
You should not try to send a image through a Intent. Rather it is better to send the Uri of the image.. And in the second activity load the image from the Uri.
I dont recommend you to pass bitmap to other activity, instead you should pass the string url and in the receiving activity you can load image from web or file.
if you really want to pass image using bitmap only then you have to Convert it to a Byte array before you add it to the intent, send it out, and decode.
Bitmap bmp = ((BitmapDrawable)thumbnail.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image",byteArray);
Then in your receiving activity you will need to add following code to receive the byte array:
byte[] byteArray = getIntent().getByteArrayExtra("image");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
now you have a bitmap you can add setImageDrawable(new BitmapDrawable(mContext.getResources(), bmp));
Thats all you need to do.
It is not a good thing to send and image into an intent, you should try to send the uri of the image instead.
But if you really want to do it, so you can get the Bitmap drawable from the image view:
Bitmap bitmap = ((BitmapDrawable) thumbnail.getDrawable()).getBitmap();
Since the bitmap is a Parcelable you can send it directly as an Extra:
intent.putExtra("RecipeThumbnail", bitmap);
Yes, it is possible.. but not recommended
1)First you have to make bitmap and bytes array from that bitmap
Bitmap bitmap = ((BitmapDrawable)thumbnail.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();
2) then you can pass it using intent
intent.putExtra("Thumbnail Image", image);
3) In receiving activity,
byte[] = getIntent.getExtra("Thumbnail Image");
Bitmap bmp = BitmapFactory.decodeByteArray(byte, 0, byteArray.length);
imageView.setImageBitmap(bmp);
Do it faster like a master :)
pass the id of the image, you have it in your resources, so why seralisin so much info if the activity b can just loading it by knowing the id...
Intent intent = new Intent(context, ActivityDetail.class);
...
intent.putExtra("imageId", R.id.recipe_img);
and on the other activity will be enough doing:
ImageView thumbnail = (ImageView) view.findViewById(yourREceivedImageId);
I'm trying to save a background from a ViewPagerParallax which can be found here : link
When i move, the background changes, and i want to take this "part" of the background and pass it to another activity.
To pass it from one to another activty i can :
Intent intent = new Intent(context, Activity2.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//Bitmap bmp = pager.getSavedBitmap().getBitmap();
Bitmap bmp = pager.getBitmap();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
intent.putExtra("image",byteArray);
context.startActivity(intent);
byte[] byteArray = getIntent().getByteArrayExtra("image");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
#SuppressWarnings("deprecation")
Drawable d = new BitmapDrawable(bmp);
layout.setBackground(d);
But know to take the part of the background i want is difficult, i'm trying to take it from the onDraw method like this :
canvas.drawBitmap(saved_bitmap, src, dst, null);
if(canvas != null){
my_bitmap = new BitmapDrawable();
my_bitmap.draw(canvas);
}
But when i use getBitmap :
public Bitmap getBitmap(){
return my_bitmap.getBitmap();
}
the image is not scaled like it was in the first activity.
Doesn't this post have a similar issue? Android Save Canvas into Bitmap
Perhaps it might help.