Activity1.class
public class CategoryActivity extends BaseActivity implements View.OnClickListener {
private RelativeLayout mReLayout;
private byte[] mImageByte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
addControl();
addEventOnClick();
mReLayout.setDrawingCacheEnabled(true);
}
private void addEventOnClick() {
findViewById(R.id.layout_category_1).setOnClickListener(this);
}
private void addControl() {
mReLayout = (RelativeLayout) findViewById(R.id.relative_category);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.layout_category_1:
startActivity();
break;
default:
break;
}
}
private void startActivity() {
Bitmap layoutBitmap = Bitmap.createBitmap(mReLayout.getWidth(), mReLayout.getHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(layoutBitmap);
mReLayout.draw(canvas);
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
layoutBitmap.compress(Bitmap.CompressFormat.PNG, 90, bStream);
mImageByte = bStream.toByteArray();
Intent mIntent = new Intent(Activity1.this, Activity2.class);
mIntent.putExtra(Constant.BYTE_IMAGE, mImageByte);
startActivity(mIntent);
}
}
Activity2.class
OnCreate
byte[] mImageByte=getIntent().getExtras().getByteArray(Constant.BYTE_IMAGE);
Bitmap bmp = BitmapFactory.decodeByteArray(mImageByte, 0, mImageByte.length);
mImageView.setImageBitmap(bmp);
When I click onClickListener. It show bug : FAILED BINDER TRANSACTION !!!
Please. Help me!
I think the reason is you're trying to put a Bitmap as an Intent extra. Although it's theoretically possible, I think the size of the Image limits such possibilities.
If you want to pass an image to another activity, then first
Save the Bitmap to a file
Send the filepath as a String to the next activity
Use the filepath from the next activity to recreate the Bitmap
If that is difficult, then try using a Singleton to store a Bitmap temporarily in memory.
Here's how to save it to disk.
First add the permission in the manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then...
File file = new File(Environment.getExternalStorageDirectory() + "imageBitmap" + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
Now send the filename to the next activity.
mIntent.putExtra("filename", "imageBitmap");
On the next activity, recreate the bitmap.
String fName = getIntent().getStringExtra("filename");
String path = Environment.getExternalStorageDirectory() + fName + ".png"
Bitmap bm = BitmapFactory.decodeFile(path);
Hope this helps.
Related
I made an application which inspects if something build correct or false by image classification. After it has been classified it triggers a screenshot. All the UI elements are on the screenshot, but the actual image I need is left out.
When I do a screenshot manually nothing is left out.
So how can I change the code to make my application do a normal screenshot?
My Launch Activity:
/** Main {#code Activity} class for the Camera app. */
public class CameraActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
}
public void startCamera(View view){
setContentView(R.layout.activity_inspection);
getFragmentManager()
.beginTransaction()
.replace(R.id.container2, Camera2BasicFragment.newInstance())
.commit();
}
}
Inspection Activity:
public class Inspection extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inspection);
}
}
And the takeScreenshot() method which is used in the Camera2BasicFragment class:
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 = getActivity().getWindow().getDecorView();
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();
}
}
Use below code to take a screenshot of the whatever the view you want,
private void captureScreen() {
View v = this.getWindow().getDecorView().findViewById(android.R.id.content);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File file = new File(extr, "fff" + ".jpg");
FileOutputStream f = null;
try {
f = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, f);
f.flush();
f.close();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Screen", "screen");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
In the code below, you can see that I have created an imageview using a bitmap. What I want to know is how I can save an image of that imageview to my camera roll. Thanks!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.key_code_zoom);
title = (TextView) findViewById(R.id.accountTitleLarge);
imageView = (ImageView) findViewById(R.id.keyCodeLarge);
Intent callingActivity = getIntent();
Bundle callingBundle = callingActivity.getExtras();
if (callingBundle != null) {
String titleText = callingBundle.getString("title");
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
title.setText(titleText);
imageView.setImageBitmap(bmp);
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
supportFinishAfterTransition();
}
});
}
To save an image in gallery, you must first get the bitmap and then save it.
private void imageToRoll(){
imageView.buildDrawingCache();
Bitmap image = imageView.getDrawingCache(); // Gets the Bitmap
MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, imagTitle , imageDescription); // Saves the image.
}
Also, set the permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you are looking for some code that will help you save the Image from the ImageView to your phone storage then the following code will help you
public String getImageFromView() {
imageview.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
imageview.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
imageview.layout(0, 0, imageview.getMeasuredWidth(), imageview.getMeasuredHeight());
imageview.buildDrawingCache(true);
//Define a bitmap with the same size as the view
Bitmap b = imageview.getDrawingCache();
String imgPath = getImageFilename();
File file = new File(imgPath);
try {
OutputStream os = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 90, os);
os.flush();
os.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, "NST");
image.put(Images.Media.DISPLAY_NAME, imgPath.substring(imgPath.lastIndexOf('/')+1));
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = file.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, file.length());
image.put(Images.Media.DATA, file.getAbsolutePath());
Uri result = mContext.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgPath;
}
you will have to provide a file path getImageFilename();this function provides the path where the file is suppose to be stored. The ContentValues will be responsible to let the images be scanned in gallery.
Hope this helps.
I have developed an app that allows the following:
1. Load image from gallery and view using ImageView.
2. Save image from ImageView into gallery.
3. An alert dialog box pops out which opens into another layout when clicked 'yes'.
I would like to pass the image bitmap from the first activity to the second activity. I have followed few example but the image is not being passed. My coding are as follows.
LoadImage.java:
public class LoadImage extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView img;
Button buttonSave;
final Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_image);
img = (ImageView)findViewById(R.id.ImageView01);
buttonSave = (Button) findViewById(R.id.button2);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
buttonSave.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
img.setDrawingCacheEnabled(true);
Bitmap bitmap = img.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/PARSE");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "Saved to your folder", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Review the Answer?");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to submit answer!")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent intent = new Intent(LoadImage.this, TestImage.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
intent.putExtra("byteArray", bs.toByteArray());
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
TestImage.java:
public class TestImage extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_image);
Intent intent = getIntent();
ImageView img = (ImageView) findViewById(R.id.ImageView01);
if(getIntent().hasExtra("byteArray")) {
ImageView previewThumbnail = new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);
previewThumbnail.setImageBitmap(bitmap);
}
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("byteArray");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
img.setImageBitmap(bmp);
}
}
The 'intent' is the second activity is grey out stating variable 'intent' is never used.
Can someone help me to resolve this issue. Any help is much appreciated. Thank you.
UPDATED!!
LoadImage.java:
buttonSave.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
img.setDrawingCacheEnabled(true);
final Bitmap bitmap = img.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/PARSE");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "Saved to your folder", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Review the Answer?");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to submit answer!")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent intent = new Intent(LoadImage.this, TestImage.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmapbytes",bytes);
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
TestImage.java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_image);
byte[] bytes = getIntent().getData().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ImageView img = (ImageView) findViewById(R.id.ImageView01);
img.setImageBitmap(bmp);
}
}
Activity
To pass a bitmap between Activites
Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);
And in the Activity class
Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
Fragment
To pass a bitmap between Fragments
SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);
To receive inside the SecondFragment
Bitmap bitmap = getArguments().getParcelable("bitmap");
Transferring large bitmap (Compress bitmap)
If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.
So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this
In the FirstActivity
Intent intent = new Intent(this, SecondActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmapbytes",bytes);
And in the SecondActivity
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Bitmap implements Parcelable, so you could always pass it in the intent:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
Yes You can send Bitmap through Intent
Intent intent =new Intent(Context ,YourActivity.class);
intent.putExtra("key",bitmap);
To receive the bitmap in YourActivity.class
Intent intent=getIntent();
Bitmap image=intent.getParcelableExtra("key");
This will work fine for Small Size bitmap
When the size of Bitmap is large it will Fail to send through Intent. Beacuse Intent are mean to send small set of data in key value pair.
For this You can send the Uri of the Bitmap through Intent
Intent intent =new Intent(Context ,YourActivity.class);
Uri uri;// Create the Uri From File Or From String.
intent.putExtra("key",uri);
In your YourActivity.class
Intent intent=getIntent();
Uri uri=intent.getParcelableExtra("key");
Create the Bitmap From the Uri.
Hope It will help you.
maybe your bitmap is too large.And you will find FAILED BINDER TRANSACTION in your logcat. So just take a look at FAILED BINDER TRANSACTION while passing Bitmap from one activity to another
I did not manage to get a picture from activity to another activity.
this is my part of the code:
this is one activity:
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText website = ((EditText) findViewById(R.id.editText));
String g = website.getText().toString();
Intent intent = new Intent(CoohseImage.this, MainActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
intent.putExtra("image", bs.toByteArray());
intent.putExtra("message", g);
startActivity(intent);
}});
And this is the second activity:
targetImage = (ImageView) findViewById(R.id.targetimage);
Intent intent = getIntent();
message = intent.getStringExtra("message");
// b = intent.getByteExtra("image", "dfdd");
((TextView)findViewById(R.id.textView)).setText(message);
if(getIntent().hasExtra("image")) {
ImageView targetImage = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(getIntent().getByteArrayExtra("image"), 0, getIntent().getByteArrayExtra("image").length);
targetImage.setImageBitmap(b);
}
A better approach would be to just share the source of your bitmap between the Activities and load the bitmap in onCreate() of the newly created Activity.
This is not recommended because it costs a lot of memory.
in first Activity
Intent i = new Intent(this, second.class);
i.putExtra("data", bitmap)
startActivity(i);
in Second Activity
Bundle b = getIntent().getExtras();
Bitmap bmp = b.getParcelable("data");
I recommed to you saving the image to disk and open it in the second activity!
1-First you need to save bitmap in a file.
2-To get bitmap from image view:
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
3-To save it in a file:
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
4- Instead of sharing sending bitmap, send outputFileUri with intent to next activity.
5-Retrieve Image from outputFileUri to image view in second activity:
Uri uri = Uri.fromFile(outputFileUri );
imageView.setImageURI(uri);
Simply pass the reference to the object
int image = R.drawable.imageinquestion;
Intent i = new Intent(Act1.this, Act2.class);
i.putExtra("IMAGE", image);
startActivity(i);
In Act2
Bundle b = getIntent().getExtras();
if(b!=null)
{
image = b.get("IMAGE");//or getInt() or getString()
}
If its a website, send the link as a String
You have a limit of data you can send via Intent using bundle, so i strongly recommend you do as Elenasys: Save in disk and open in the target activity.(You can use the intent to send the path).
In My Code The image is not open in ImageView from sdcard i already checked the permissions in 'manifest.xml'.
Same if i try to open it using static name then it will showed by ImageView but not dynamically.
Main Activity
private OnClickListener OnCapture = new OnClickListener() {
#Override
public void onClick(View v) {
String time = mCamUtils.clickPicture();
nextActivity = new Intent(MainActivity.this,EffectActivity.class);
nextActivity.putExtra("ImageName", time);
startActivity(nextActivity);
finish();
}
};
EffectActivity
public class EffectActivity extends Activity {
Intent getActivity = null;
ImageView image = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.effectactivity);
getActivity = getIntent();
String name = getActivity.getStringExtra("ImageName");
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
Toast.makeText(getApplicationContext(), path, Toast.LENGTH_LONG).show();
image = (ImageView) findViewById(R.id.imageView1);
File f = new File(path);
byte[] b = new byte[(int)f.length()];
if(f.exists())
{
try
{
if(f.exists())
{
FileInputStream ff = new FileInputStream(f);
ff.read(b);
Bitmap g = BitmapFactory.decodeFile(path);
image.setImageBitmap(g);
ff.close();
}
else
{
Toast.makeText(getApplicationContext(), "ELSE", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
}
}
}
}
I am trying to open image which i saved in before this activity and i catch the name of image here but that does not show the image.
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
In this line try changing "JPG" into "jpg".i think your file extension might be in lowercase letter and it might say f.exists false.
Hope it will help.
String fname = "Pic-" + System.currentTimeMillis() + ".png";
File image= new File(imagesFolder, fname);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
picturePath=image.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions);
imageView.setImageBitmap(bitmap);
try this code