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);
Related
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!!
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 a dialog with some TextViews and ImageViews inside. Now I want to share this with the Share Intent. Is this possible? Can I share a dialog or convert it first to a bitmap and then share it?
You can use this method.
public static Bitmap TakeBitmapFromDialog(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width , height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
OR
simply use this.
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
UPDATE:
if you don't want to use that then use this.
Bitmap cs = null;
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
cs = Bitmap.createBitmap(view.getDrawingCache());
Canvas canvas = new Canvas(cs);
view.draw(canvas);
canvas.save();
view.setDrawingCacheEnabled(false);
If you want to share that bitmap you need to insert in Media Images like,
String path = Images.Media.insertImage(getContentResolver(), cs,
"MyImage", null);
Uri file = Uri.parse(path);
Now for sharing,
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, file);
startActivity(Intent.createChooser(sharingIntent,
"Share image using"));
Create a custom dialog separately using activity context and use it in a separate activity.
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.
The goal is to convert a Bitmap to a byte [], pass it between activities in a Bundle of data, then reconvert it back to a Bitmap at a later stage for display in an Imageview.
The issue is that whenever I try this, I just get a null bitmap and the non-descriptive, unhelpful log output:
12-07 17:01:33.282: D/skia(2971): --- SkImageDecoder::Factory returned null
I have looked at the following solutions:
Solution supplies the bitmap to byte[] code used
Highlighted that copyPixelsToBuffer() is essential over .compress
(Especially seeing as it is not necessary in this case).
I have run up the following test case which definitely narrows down the problem to the converting and restoring code. Based on my debugging, there is correct decoding, the byte array is the correct size and full, Bitmap configs are forced to be the same, decodeByteArray is just failing:
package com.example.debug;
import java.nio.ByteBuffer;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
RelativeLayout rl = null;
RelativeLayout.LayoutParams rlp = null;
ImageView ivBef = null;
ImageView ivAft = null;
Bitmap bmBef = null;
Bitmap bmAft = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TEST
BitmapFactory.Options bmo = new BitmapFactory.Options();
bmo.inPreferredConfig = Config.ARGB_8888;
bmBef = BitmapFactory.decodeFile("/mnt/sdcard/Debug/001.png", bmo);
byte[] b = bitmapToByteArray(bmBef);
bmAft = BitmapFactory.decodeByteArray(b, 0, b.length, bmo);
LinearLayout ll = new LinearLayout(this);
ivBef = new ImageView(this);
ivBef.setImageBitmap(bmBef);
ivAft = new ImageView(this);
ivAft.setImageBitmap(bmAft);
ll.addView(ivBef);
ll.addView(ivAft);
setContentView(ll);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public static byte[] bitmapToByteArray(Bitmap bm) {
// Create the buffer with the correct size
int iBytes = bm.getWidth() * bm.getHeight() * 4;
ByteBuffer buffer = ByteBuffer.allocate(iBytes);
// Log.e("DBG", buffer.remaining()+""); -- Returns a correct number based on dimensions
// Copy to buffer and then into byte array
bm.copyPixelsToBuffer(buffer);
// Log.e("DBG", buffer.remaining()+""); -- Returns 0
return buffer.array();
}
}
The before Imageview correctly displays the image, the after ImageView shows nothing (as you would expect with a null bitmap
You are passing Bitmap into Intent and get bitmap in next activity from bundle, but the problem is if your Bitmap/Image size is big at that time the image is not load in next activity.
Use below 2 Solutions to solve this issue.
1) First Convert Image into Byte Array and then pass into Intent and in next activity get byte array from Bundle and Convert into Image(Bitmap) and set into ImageView.
Convert Bitmap to Byte Array:-
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Pass byte array into intent:-
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);
Get Byte Array from Bundle and Convert into Bitmap Image:-
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
2) First Save image into SDCard and in next activity set this image into ImageView.
The following method works perfectly with me, give it a try..
public byte[] convertBitmapToByteArray(Context context, Bitmap bitmap) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(bitmap.getWidth() * bitmap.getHeight());
bitmap.compress(CompressFormat.PNG, 100, buffer);
return buffer.toByteArray();
}
try this:
bmBef = BitmapFactory.decodeFile("/mnt/sdcard/Debug/001.png", bmo);
ByteArrayOutputStream baos= new ByteArrayOutputStream();
bmBef .compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] byteArray = baos.toByteArray();