I connected to the camera via API. When a function
camera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
returns an array of byte [] data. If I understand correctly, this is our picture. How can I pass this array of bytes by Intent and set the resulting image next Activiti?
You could try:
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length());
Then assuming the data you want to pass implements Serializable(which it should), passing it through an Intent should be as simple as:
from one activity:
i.putExtra("image", bitmap);
startActivity(i);
into the next next activity:
Intent i = getIntent();
Bitmap data = (Bitmap)i.getSerializableExtra("image");
i have success whit this way
First part
public void takePicture(View view) {
camera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Intent intent = new Intent(context, AcceptNotAccept.class);
intent.putExtra("picture", data);
startActivity(intent);
}
}
}
and then got this Intent
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accept_not_accept);
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
((ImageView)findViewById(R.id.ivForAcceptPicture)).setImageBitmap(bitmap);
}
The idea here is to save the image into your External/Internal memory (prefer: External like SD) and use the full path of the image e.g.
Intent i = new Intent(...);
i.putExtra("myimage","path://example.path/image.jpg");
startActivity(i);
The receiving activity can get the image by calling its path:
String imagePath = getIntent().getStringExtra("myimage");
Related
I am receiving a NullPointerException error on my getIntent() when trying to pass a bitmap from one activity to an another activity
First Activity
public void processor(View view)
{
BitmapDrawable drawable = (BitmapDrawable)imageCapt.getDrawable();
Bitmap yeet = drawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yeet.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
Intent intent = new Intent(camera_activity.this, ClassifierTask.class);
intent.putExtra("picture", bytes);
startActivity(intent);
}
Receiving Activity
public class ClassifierTask extends AsyncTask<Void,Void,Void> {
static Context context;
#Override
public void onPreExecute() {
super.onPreExecute();
}
#Override
public Void doInBackground(Void... param) {
Intent intent = ((Activity)context).getIntent();
byte[] bytes = intent.getByteArrayExtra("picture");
m_bitmapForNn = BitmapFactory.decodeByteArray(bytes,0, bytes.length);
The error I receive is
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.app.Activity.getIntent()' on a null object reference
Any advice or solution for this, would be appreciated
I have a very good way
You create a new one Class,and new static
public class Data {
public static byte[] bytes;
}
or setup HashMap,ArrayList....
you just put data and read In another place
Data.bytes[0]=
When I try to get the result from the camera I keep getting a "NullPointerException: uri" at the line:
InputStream stream = getContentResolver().openInputStream(data.getData());
from the code:
if (requestCode == CAMERA_PIC_REQUEST) {
try {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
pic.setImageBitmap(thumbnail);
InputStream stream = getContentResolver().openInputStream(data.getData());
bitmapPic = BitmapFactory.decodeStream(stream);
Being pic an ImageViewer and the image is successfully placed in the ImageViewer I can't seem to find the reason as to why this is not working.
Also here's the code for the Intent that starts the image capturer.
pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
And the part of the code that I will use it on after this is working, or at least trying to:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmapPic.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] data = baos.toByteArray();
mStorageRef.child(animal.getPictureID()).putBytes(data);
Being the last line Firebase related.
Also bitmapPic is a Bitmap.
Edit 1: Tried a suggestion by adding global variable:
private FileProvider mImageUri;
then
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(Intent.EXTRA_STREAM, mImageUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
But it says that putExtra combination doesn't exist. Not sure if that's what you meant.
Edit 2: Managed to get it working. As of now it only sends the Thumbnail but at least it's something here's how I did it:
if (requestCode == CAMERA_PIC_REQUEST) {
try {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
pic.setImageBitmap(thumbnail);
encodeBitmap(thumbnail);
}
where:
ByteArrayOutputStream baos;
public void encodeBitmap(Bitmap bitmap) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
}
And finally to send it to firebase I used this:
byte[] data = baos.toByteArray();
mStorageRef.child(animal.getPictureID()).putBytes(data);
I have Activity A, B and C. In Activity C, it has an image and caption. The image and caption will be return to B when ok button is clicked. In activity b, it will return both to activity A.
Activity C
ok.setOnClickListener(new View.OnClickListener() // ok button to return image and caption to B
{
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity B
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c); // caption can show in txt1
viewImage.setImageBitmap(Global.img); // image from C can show in viewImage
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
b.setOnClickListener(new View.OnClickListener() { // button to return image and caption to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
returnIntent.putExtra("c",c); // return caption
returnIntent.putExtra("globalImg",Global.img);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap b = Global.img
if (requestCode==1) {
caption = data.getStringExtra("c"); // caption from A
v.setImageBitmap(Global.img) // image from C
}else if {.....}
}
Global.java
public class Global {
static Bitmap img;
}
When I click button b in Activity B, I get this
11-05 17:26:47.114 6031-6031/com.example.project.project
E/JavaBinder﹕ !!! FAILED BINDER TRANSACTION !!!
Provided what you are trying to do is simply to pass along the data returned from C->B on to A, why don't you just get the string again in your onClick and put it into your intent?
You could store the text in a String member, or, as the code looks now, even get it back from the TextView:
Intent returnIntent = new Intent();
returnIntent.putExtra("text", txt1.getText().toString);
setResult(Activity.RESULT_OK, returnIntent);
The image is being stored as a static in a global object, which honestly is horrible, but you could of course access that as well from your onClickListener. You should however seriously consider returning the bitmap data in some other way, the most straightforward probably being utilizing that Bitmaps implement the Parcelable interface, and Intents can hold Parcelables as extras, so in theory you can just do putExtra("img", bitmap) and on the receiving end do intent.getParcelableExtra("img").
However, if the bitmap is large this might fail, and it might be better to store the bitmap to a resource such as a file, and pass the location of the file instead. You may also get a way with something like what you did with your static member in the Global class, but 1) you must be careful to remove the object after passing it back or the static reference will waste memory and 2) make sure you don't use this reference incorrectly, e.g. from multiple places simulatenously. A more robust solution is to make sure you create a unique ID for each bitmap and store it in a cache (for example a HashMap with the Bitmaps hashCode() as the key) and identify it by id.
public class BitmapStore {
private static final HashMap<Integer, Bitmap> BITMAPS= new HashMap<>();
public static Bitmap getBitmap(int id) {
return BITMAPS.remove(id);
}
public static int putBitmap(Bitmap b) {
int id = b.hashCode();
BITMAPS.put(id, b);
return id;
}
}
Using this, you could put the ID of your bitmap in your intent:
intent.putExtra("imageId", BitmapStore.putBitmap(bitmap));
setResult(RESULT_OK, intent);
and in onActivityResult:
Bitmap b = BitmapStore.getBitmap(intent.getIntExtra("imageId", 0));
This bitmap store is not persistant but it should be pretty safe to use as an intermediate store in the transition between two activities. It's also possible to generalize to any kind of object implementing a valid hashCode/equals contract.
try comment this line:
//returnIntent.putExtra("globalImg",Global.img);
in your Activity B
You can use Global.img for all Activity and not use intent
Added:
v.setImageBitmap(Global.img); -> nullPointerExeption becouse v is not initialize
Added:
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inPreferredConfig = Config.RGB_565;
bitmapOptions.inDither = true;
For "Out of memory" error.
I am trying to pass a byte array between activities using startActivity and onActivityResult. The byte array is null when returning to onActivityResult and I cannot figure out why. This happens no matter how large the byte array is so I don't think it has to do with size. Also, I am passing a byte array of approximately the same size using intents successfully in another area. The code:
In post activity:
public void callCropperIntent() {
/* call the cropper to crop a photo from the gallery */
intent = new Intent(getApplicationContext(), Cropper.class);
startActivityForResult(intent, CROP_GALLERY_PICTURE);
}
In cropper activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
File croppedImageFile = new File(getFilesDir(), "test.jpg");
try {
if ((requestCode == REQUEST_PICTURE) && (resultCode == RESULT_OK)) {
/** When the user is done picking a picture, we'll start the CropImage Activity,
* setting the output image file and size to 640 X 640 pixels square.
*/
Uri croppedImage = Uri.fromFile(croppedImageFile);
CropImageIntentBuilder cropImage = new CropImageIntentBuilder(640, 640, croppedImage);
cropImage.setSourceImage(data.getData());
cropImage.setOutputQuality(100);
startActivityForResult(cropImage.getIntent(this), REQUEST_CROP_PICTURE);
}
else if ((requestCode == REQUEST_CROP_PICTURE) && (resultCode == RESULT_OK)) {
/* when we are done cropping, send it back to PostActivity */
//imageView.setImageBitmap(BitmapFactory.decodeFile(croppedImageFile.getAbsolutePath()));
Bitmap bmp = BitmapFactory.decodeFile(croppedImageFile.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
//this set bitmap works so I know the bitmap is valid
//test
//imageView.setImageBitmap(bmp);
byte[] imageData = stream.toByteArray();
//bmp.recycle();
Intent intent = getIntent();
intent.putExtra("image", imageData);
setResult(RESULT_OK, intent);
finish();
}
}
Back in post activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
byte[] croppedData;
/* check the request code */
if (requestCode == CROP_GALLERY_PICTURE) {
/* ensure the request was successful */
if (resultCode == RESULT_OK) {
/* The user picked and cropped a photo */
/* retrieve photo from cropping activity */
Intent intent = getIntent();
croppedData = data.getByteArrayExtra("image");
/* bytes ready to be sent to pg. 2 of posting process */
callPostActivityPg2Intent(croppedData);
}
}
}
I think in the cropper class,before finish() you should create a new instance of Intent class instead of obtaining one by calling getintent().
Ex: Intent intent = new Intent();
intent.putExtra ()....
I've written a program in Java that takes in an image file and manipulates the image. Now I'm trying to access the camera so that I can take the photo and give it to the image processing program however I'm lost as to how to do this. I've read the information about the camera class and how to ask for permissions but I don't know how to actually take the photo. If anyone has any tips on where I should begin or if they know of a good tutorial I'd really appreciate it. Thanks!
Google is your best friend, here are some tutorials:
Using the camera
How-To Program The Google Android Camera To Take Pictures
Take Picture from Camera Emulator
camera
First edit your AndroidManifest.xml, add the camera permission:
<uses-permission android:name=”android.permission.CAMERA”/>
Camera service has to be opened and closed:
Camera camera = Camera.open();
//Do things with the camera
camera.release();
You can set camera settings, e.g.:
Camera.Parameters parameters = camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
camera.setParameters(parameters);
To take a picture:
private void takePicture() {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
// TODO Do something when the shutter closes.
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] _data, Camera _camera) {
// TODO Do something with the image RAW data.
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] _data, Camera _camera) {
// TODO Do something with the image JPEG data.
}
};
Do not forget to add the camera layout to your main layout xml.
there are many ways by which u can do this....
One of the better way which i think is the short and simple is to on Button Click u can call intent which opens ur inbuilt camera view... here is the sample code...
public class CameraDemo extends Activity {
Button ButtonClick;
int CAMERA_PIC_REQUEST = 2;
int TAKE_PICTURE=0;
Camera camera;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ButtonClick =(Button) findViewById(R.id.Camera);
ButtonClick.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View view)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if( requestCode == CAMERA_PIC_REQUEST)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image =(ImageView) findViewById(R.id.PhotoCaptured);
image.setImageBitmap(thumbnail);
}
else
{
Toast.makeText(demo.this, "Picture NOt taken", Toast.LENGTH_LONG);
}
}
}
..............................................................
Go through it and, if u have any problem feel free to ask....
rakesh
There are two methods to take photo for your android application
1)Using Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
2) Creating a customized camera activity. For that you need following steps
* Detect and Access Camera
* Create a Preview Class
* Build a Preview Layout
* Capture and Save Files
* Release the Camera
You may also refer the following links:
http://developer.android.com/guide/topics/media/camera.html
http://developer.android.com/reference/android/hardware/Camera.html
the most important method is:
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] imageData, Camera c) {
}
};
This method is called when a picture is taken.
Here is a good tutorial on this topic: http://www.brighthub.com/mobile/google-android/articles/43414.aspx
hmm... or maybe you need this one:
Camera mCamera;
...
public void onClick(View arg0) {
mCamera.takePicture(null, mPictureCallback, mPictureCallback);
}
Here is one more example: http://snippets.dzone.com/posts/show/8683