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
Related
I have some troubles to display images in OpenGL.
Actually I'm able to display images from gallery in opengl. The problem occurs when I try to show one from the camera.
For me, OpenGL have to display the image from the camera as it does with the gallery ones. Obviously I'm making something wrong.
Any help will be appreciated.
Intent from gallery:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/");
startActivityForResult(intent, 2);
Intent from camera:
Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) != null) {
File imagen = controler.createPhotoFile(getExternalFilesDir(Environment.DIRECTORY_PICTURES));
if (imagen != null) {
photoUri = FileProvider.getUriForFile(this, "my.fileprovider", imagen);
takePic.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(takePic, 1);
}
}
This is my onActivityResult where I send the URI to a method which convert it to a bitmap and send it.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 1:
sendImagenPanel(photoUri);
break;
case 2:
sendImagenPanel(data.getData());
break;
}
}
}
private void sendImagenPanel(Uri uri) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
final Bitmap imagen = controler.getCroppedBitmap(controler.scaledBitmap(bitmap, 256));
final CasillaOG casilla = ((GLSurfacePanel) gLViewPanel).getRendererPanel().getCuboSelected();
gLViewPanel.queueEvent(new Runnable() {
#Override
public void run() {
casilla.loadNewTexture(imagen);
casilla.setImagen(imagen);
}
});
gLViewPanel.requestRender();
}
In case someone is interested. I realize that the problem is not on the method that calls OpenGL. If I run the same code on the onActivityResult works from the gallery requestCode but not on the camera one, in my Samsung Galaxy Tab A. Why I mention my device? because if I run the app on a Huawei P9 lite, the gallery images are not display either. In both cases appears the next problem on the console:
call to opengl es api with no current context (logged once per thread)
After search that problem, I suppose that the intents of the camera and gallery use OpenGL and its originate a conflict with my own OpenGL environment.
Finally, I opted to set a bitmap field and add the texture in on the onDrawFrame. Obviously, with a boolean to make it one time.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have my main Activity in which I have a few Buttons.
One of them is supposed to open the Camera.
To make it cleaner I am using View.onClick(), so I will just have the Button on the main Activity and the rest will be managed by another other class (Camactivity).
In my main Activity :
Button btnrep = (Button)findViewById(R.id.button3);
btnrep.setOnClickListener(new Camactivity(this));
and in my
public class Camactivity extends Activity implements View.OnClickListener
private File imageFile;
private Context appContext;
public MainActivity_1(Context context)
{
appContext = context;
}
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);//use intent and pass in mediastore
//mediastore is a databases where image and video are stores and link
imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "BreedingGround.bmp");
/*link to a directory - pass in directory where you want to save the pictures and names of the file*/
Uri tempuri = Uri.fromFile(imageFile);//Convert imageFile to a Uri
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, tempuri);//location where u want the image file to be save after taking photo
intent.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1);//quality of out image, 1 means high quality image
startActivityForResult(intent, 0);//Request code 0 to identify who send the request
}
However I am getting a null pointer error at startActivityForResult(intent, 0);
FATAL EXCEPTION: main Process: com.example.mohit.softeng, PID: 22075
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:97)
at com.example.mohit.softeng.MainActivity_1.onClick(MainActivity_1.java:60)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
You are more than welcome to define a View.OnClickListener subclass, but
there's really no reason I see to have Camactivity at all, so just implement View.OnClickListener onto MainActivity.
Besides, you will likely want the result from startActivityForResult within MainActivity's onActivityResult, not Camactivity.
So, with that suggestion
Button btnrep = (Button)findViewById(R.id.button3);
btnrep.setOnClickListener(this);
If you already have your Activity implementing an OnClickListener, then add an if-statement to check which button is clicked.
#Override
public void onClick(View view) {
switch (v.getId()) {
case R.id.button3:
openCamera();
}
}
private void openCamera() {
// That other code in Camactivity
}
Alternative answer... still not using new to make an Activity class.
Button btnrep = (Button)findViewById(R.id.button3);
btnrep.setOnClickListener(new View.onClickListener() {
#Override
public void onClick(View v) {
Intent cam = new Intent(MainActivity.this, Camactivity.class);
startActivityForResult(cam, 0); // If you need the result in MainAcivity, pass it back from camActivity
// else, just startActivity(cam);
}
});
Then, update Camactivity to start the camera intent as soon as it is created.
public class Camactivity extends Activity {
private File imageFile;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);//use intent and pass in mediastore
//mediastore is a databases where image and video are stores and link
imageFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "BreedingGround.bmp");
/*link to a directory - pass in directory where you want to save the pictures and names of the file*/
Uri tempuri = Uri.fromFile(imageFile);//Convert imageFile to a Uri
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, tempuri);//location where u want the image file to be save after taking photo
intent.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1);//quality of out image, 1 means high quality image
startActivityForResult(intent, 0);//Request code 0 to identify who send the request
}
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
// TODO: Handle camera intent result
}
}
}
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");
I'm trying to get a program to let the user to import a custom background.
Here's where I'm at:
I have the getDrawable function taking another function as an argument:
mDrawableBg = getResources().getDrawable(getImage());
getImage() is suppose to return a integer referencing the selected image, here is the code (so far) for that function:
public int getImage(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 10);
}
This is suppose to open the gallery and let the user select an image. I would then use mDrawableBg to set the background. I'm not sure how to return a reference ID to that selected image though. Any suggestions?
Try this:
String pathName = "selected Image path";
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
BitmapDrawable bd = new BitmapDrawable(res, bitmap);
View view = findViewById(R.id.container);
view.setBackgroundDrawable(bd);
The way you're attempting to do it is not possible, I'm afraid. One of the things you'll want to learn as a new Android developer is how the cycle between activities works. In your case, you're running an Activity that calls upon an Intent to get data from it. However, in the Android API, an Intent can only be referenced on its own time. This means you can't use your getImage() method the way you had tried.
There is hope, though!
What you first need to do is call the Intent. You will do this through the code you have now in getImage():
public void getImage() { // This has to be a void!
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 10);
}
This method will now start the Image Picker that you want users to select from. Next, you have to catch what is returned. This cannot be returned from your getImage() method, but instead must be collected from elsewhere.
You must implement the below method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
final int SELECT_PICTURE = 1; // Hardcoded from API
if (requestCode == SELECT_PICTURE) {
String pathToImage = data.getData().getPath(); // Get path to image, returned by the image picker Intent
mDrawableBg = Drawable.createFromPath(pathToImage); // Get a Drawable from the path
}
}
}
Lastly, instead of calling mDrawableBg = getResources().getDrawable(getImage());, just call getImage();. This will initialize the Image Picker.
Some reading:
Android Activity (notably stuff about Intents and getting a result back)
Android Drawable
Getting a Drawable from a path
More on the Image Picker Intent
Good luck!
I'm not sure, but if you mean you don't know how to receive results from that intent, you can use :
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
if (requestCode == 10)
{
// DoSomething
}
}
}
I have an application that allow users to choose picture from native gallery then I show this image in image view widget.
My question is:
1-i have to send this image to another Activity. How can i do it.
2-in the receiver Activity i should show it in image view widget as in image not link or Something
I tried this code but it gives me a RunTime Error
Bitmap image = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.RGB_565);
view.draw(new Canvas(image));
String url = Images.Media.insertImage(getContentResolver(), image,"title", null);
Just follow the below steps...
Uri uri = null;
1) on any click event use the below code to open native gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);
This will open gallery select picture will return you to your activity. OnActivity result.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
try {
uri = Uri.parse(data.getDataString());
imageView.setImageUri(uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
break;
}
}
2) Also instead of passing the image you can pass the URI to next activity as you pass string and inthe secont activity you get it using intent.
Intent i = new Intent(this, Second.class);
i.putExtra("URI", uri.toString() );
startActivity(i);
and in the second activity
String uri = getIntent().getStringExtra("URI");
Now you have string just set it to the image view like below
imageView.setImageUri(Uri.parse(uri));
Use intent putExtra and send uri of the image user selected in Acvtivity1 and in second activity use intent getExtra to read the uri
Refer this answer https://stackoverflow.com/a/7325248/308251
Maybe this is not what you're looking for and it's a bit poor but saved my life when I needed to pass objects between Activities.
public class MagatzemImg {
private static MagatzemImg instance = null;
private static Bitmap img;
public MagatzemImg(){
img=null;
}
public static MagatzemImg getInstance() {
if (instance == null)
instance = new MagatzemImg();
return instance;
}
public static void setImg(Bitmap im){
img = im;
}
public static Bitmap getImg(){
Bitmap imgAux = img;
img = null;
return imgAux;
}
}
And then from the new activity:
MagatzemImg.getInstance();
image = MagatzemImg.getImg();
You can 'assure' to the new Activity that the image exists inside the Static Class through putExtra("image",true) or something else you prefer, like checking if the "image" is null.