How to save a canvas into a bitmap - java

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.

Related

How to create a bitmap from a screenshot of a view bigger than the screen?

I'm trying to create a bitmap that takes a "screenshot" of a view but who's bigger than the screen size, I need a bitmap of 1500px x 2115px to turn it into a pdf after that, but on phone is too big.
Here is my code which works if I use it with a tablet but not with the phone :
public void layoutToImage(View view, String imageName) {
view.setDrawingCacheEnabled(true);
view.measure(View.MeasureSpec.makeMeasureSpec(1500, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(2115, View.MeasureSpec.EXACTLY));
view.layout(0, 0, 1500, 2115);
view.buildDrawingCache(false);
Bitmap bm = view.getDrawingCache();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File mFileImg = new File(Environment.getExternalStorageDirectory() + File.separator + imageName);
try {
mFileImg.createNewFile();
FileOutputStream fo = new FileOutputStream(mFileImg);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
}
Is this possible to achieve the same result on the tablet as on the phone? Any solution or suggestion will be helpful,
thank you.

How to send image from one activity to another in android

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

Display Image with Universal ImageLoader with Bitmap

I wonder how to display image if I have a Bitmap and don't want to give as a parameter URL to image using Universal ImageLoader library.
Bitmap img = getDefaultBitmap();
ImageLoader.getInstance().displayImage(img); // I need something like this (for example with parameters to display image like width and height)
Firstly,
you have to save bitmap and then u can pass that path to show that bitmap into imageview using imageloader.
//-- Saving file
String filename = "pippo.jpg";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
//-- show bitmap to imageview
imageLoader.displayImage(dest.getAbsolutePath(), imageView);

Android, Java: Share a dialog

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.

Android: Bitmap to Byte Array and back: SkImageDecoder::Factory returned null

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

Categories

Resources