Rectangle 27 2

You need to specify a path for the camera intent to store the real image. Because the data.getExtras().get("data"); just get a thumbnail from the real image.

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

// Create the File where the photo should go
File photoFile = createImageFile();


if (photoFile != null) {
   takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
   startActivityForResult(takePictureIntent, 1);
}

This is the method for create the File:

private File createImageFile() {

        long timeStamp = System.currentTimeMillis();
        String imageFileName = "NAME_" + timeStamp;
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        return image;
    }

Then you can read the real path of the created picture.

android - Camera Image is too small - Stack Overflow

android bitmap android-camera bytearray android-camera-intent
Rectangle 27 10

Most often, but not always, there is correspondence between picture aspect ratios and preview aspect ratios. You can be assured that at least some of them are classic 4:3 ratios (e.g. 640x480). Support for 16:9 is also widely available.

The screen may have different aspect ratio. To fill it with a camera image correctly, it is widely accepted to add black margins (same approach is used in YouTube). Alternatively, you may crop the camera image to fill the whole screen.

Note that the screen size (as reported in tech specs for the variety of devices) is not always actually available for your image display. For example, the system menus, and title bar, etc. may take their share of the screen real estate. The immersive mode is available on some devices, and its behavior depends on the system version. You may expect that future developments of Android, e.g. second screen support, will make the game even more interesting.

Even if your camera supports different "wide" picture sizes, 1280x720 preview and 2560x1440 picture may be the best match, both precisely at 16:9. Usually, the quality of picture at small size is not significantly better than preview at that same size, so you may choose to save the preview frame if 1280x720 is what you really need.

takePicture()

Camera in Android, how to get best size, preview size, picture size, v...

android image camera android-camera
Rectangle 27 369

Here's an example activity that will launch the camera app and then retrieve the image and display it.

package edu.gvsu.cis.masl.camerademo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MyCameraActivity extends Activity {
    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.imageView = (ImageView)this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.button1);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, CAMERA_REQUEST); 
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {  
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
        }  
    } 
}

Note that the camera app itself gives you the ability to review/retake the image, and once an image is accepted, the activity displays it.

Here is the layout that the above activity uses. It is simply a LinearLayout containing a Button with id button1 and an ImageView with id imageview1:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/photo"></Button>
    <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>

</LinearLayout>

and if camera is optional to your app functionality. make sure to set require to false in the permission. like this

Bitmap photo = (Bitmap) data.getExtras().get("data"); Its giving a Null pointer expection. When i open the app and click Capture.. it goes to the camera app and after 2-4 secs the whole thing crashes.

I suppose to be on the safe side we should be checking to see if resultCode == Activity.RESULT_OK in the onActivityResult() method. As to why the camera is crashing, we'd have to see a stack trace.

<uses-feature/>
android:required="false"
<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>

Also note that Bitmap photo = (Bitmap) data.getExtras().get("data"); does not grab the image that was taken. It grabs a thumbnail of the image that was taken.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

android - Capture Image from Camera and Display in Activity - Stack Ov...

android image camera capture
Rectangle 27 369

Here's an example activity that will launch the camera app and then retrieve the image and display it.

package edu.gvsu.cis.masl.camerademo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MyCameraActivity extends Activity {
    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.imageView = (ImageView)this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.button1);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, CAMERA_REQUEST); 
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {  
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
        }  
    } 
}

Note that the camera app itself gives you the ability to review/retake the image, and once an image is accepted, the activity displays it.

Here is the layout that the above activity uses. It is simply a LinearLayout containing a Button with id button1 and an ImageView with id imageview1:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/photo"></Button>
    <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>

</LinearLayout>

and if camera is optional to your app functionality. make sure to set require to false in the permission. like this

Bitmap photo = (Bitmap) data.getExtras().get("data"); Its giving a Null pointer expection. When i open the app and click Capture.. it goes to the camera app and after 2-4 secs the whole thing crashes.

I suppose to be on the safe side we should be checking to see if resultCode == Activity.RESULT_OK in the onActivityResult() method. As to why the camera is crashing, we'd have to see a stack trace.

<uses-feature/>
android:required="false"
<uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>

Also note that Bitmap photo = (Bitmap) data.getExtras().get("data"); does not grab the image that was taken. It grabs a thumbnail of the image that was taken.

android - Capture Image from Camera and Display in Activity - Stack Ov...

android image camera capture
Rectangle 27 2

If somebody experiences problems with ExifInterface on Android 4.4 (KitKat) for getting the orientation, it might be because of wrong path got from the URI. See a solution for propoer getPath in Stack Overflow question Get real path from URI, Android KitKat new storage access framework

Why does an image captured using camera intent gets rotated on some de...

android image camera rotation android-camera-intent
Rectangle 27 2

If somebody experiences problems with ExifInterface on Android 4.4 (KitKat) for getting the orientation, it might be because of wrong path got from the URI. See a solution for propoer getPath in Stack Overflow question Get real path from URI, Android KitKat new storage access framework

Why does an image captured using camera intent gets rotated on some de...

android image camera rotation android-camera-intent
Rectangle 27 1

As the OP stated, some devices don't rotate the image, some rotate it 90 degrees, some 180, ..etc. So always rotating it 90 would be incorrect in some cases.

Why does an image captured using camera intent gets rotated on some de...

android image camera rotation android-camera-intent
Rectangle 27 1

As the OP stated, some devices don't rotate the image, some rotate it 90 degrees, some 180, ..etc. So always rotating it 90 would be incorrect in some cases.

Why does an image captured using camera intent gets rotated on some de...

android image camera rotation android-camera-intent
Rectangle 27 3

Unfortunately Java does not support serial ports on its own - you need an external library for that. I would suggest taking a look at the RXTX library, which seems to be somewhat of a defacto standard these days.

Video sensor chips usually have relatively simple communication interfaces on their own (i.e. without a bridge chip). Usually it boils down to setting the image parameters, initiating the actual image data transfer and then reading a number of bytes into a buffer. Sometimes an image data start or end signature may be involved, but that's about it.

It should not be too hard if you have all the documentation for you chip at hand - I have occasionally done something similar in C without any documentation...

Once you have read the image to a byte array, you might be able to use the BufferedImage class to make it usable for Java. That said, I have not been able to determine if Java supports anything but ARGB variations - you may have to do the color-space conversion on your own (or via a third-party library, I suppose) if you want to use a non-RGB mode in your sensor.

thanks I know how to read from a COM port using RXTX library but the what I need is to process that data from the COM port into an image in Java

Code edited and uploaded..However, is there a way I could detect the end of image to stop the while loop which is while(inputStream.available () > 0)

@stud91: well, the obvious way would be to count the number of bytes. Raw images have a fixed byte size, depending on the resolution and the bytes/pixel. Beware of padding bits in formats with e.g. 12 bits/pixel. Some sensors also have delimiter byte sequences. You should check your sensor documentation for details on its supported output formats...

The documentation found here says that the resolution is 356x292 and the image output that i have programmed is to be 8-bit so the image size should be 356x292x8 = 831,616 bits = 103952 bytes. (people.ece.cornell.edu/land/courses/ece4760/FinalProjects/s2011/)

java - Camera image processing - Stack Overflow

java image image-processing
Rectangle 27 8

Here is code I have used for Capturing and Saving Camera Image then display it to imageview. You can use according to your need.

You have to save Camera image to specific location then fetch from that location then convert it to byte-array.

Here is method for opening capturing camera image activity.

private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;

private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }
@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);                
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            } 
        }

Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.

private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

I tried this and put captureImage() in the onClick from the onClickListener and not working. I am working with a FragmentDialog... any ideas?

android - Capture Image from Camera and Display in Activity - Stack Ov...

android image camera capture
Rectangle 27 8

Here is code I have used for Capturing and Saving Camera Image then display it to imageview. You can use according to your need.

You have to save Camera image to specific location then fetch from that location then convert it to byte-array.

Here is method for opening capturing camera image activity.

private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;

private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }
@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);                
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            } 
        }

Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.

private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

I tried this and put captureImage() in the onClick from the onClickListener and not working. I am working with a FragmentDialog... any ideas?

android - Capture Image from Camera and Display in Activity - Stack Ov...

android image camera capture
Rectangle 27 1

This maybe goes without saying but always remember that you can handle some of these image handling issues on your server. I used responses like the ones contained in this thread to handle the immediate display of the image. However my application requires images to be stored on the server (this is probably a common requirement if you want the image to persist as users switch phones).

The solutions contained in many of the threads concerning this topic don't discuss the lack of persistence of the EXIF data which doesn't survive the Bitmap's image compression, meaning you'll need to rotate the image each time your server loads it. Alternatively, you can send the EXIF orientation data to your server, and then rotate the image there if needed.

It was easier for me to create a permanent solution on a server because I didn't have to worry about Android's clandestine file paths.

Can you rotate it once at image capture time and save it that way so it never needs to be rotated again?

Yea you can and that's actually the process I ended up implementing in the end. I was having trouble getting the file path from the image on the Android phone that would allow me to do that. This is the answer that helped: stackoverflow.com/a/36714242/5443056

Why does an image captured using camera intent gets rotated on some de...

android image camera rotation android-camera-intent
Rectangle 27 1

This maybe goes without saying but always remember that you can handle some of these image handling issues on your server. I used responses like the ones contained in this thread to handle the immediate display of the image. However my application requires images to be stored on the server (this is probably a common requirement if you want the image to persist as users switch phones).

The solutions contained in many of the threads concerning this topic don't discuss the lack of persistence of the EXIF data which doesn't survive the Bitmap's image compression, meaning you'll need to rotate the image each time your server loads it. Alternatively, you can send the EXIF orientation data to your server, and then rotate the image there if needed.

It was easier for me to create a permanent solution on a server because I didn't have to worry about Android's clandestine file paths.

Can you rotate it once at image capture time and save it that way so it never needs to be rotated again?

Yea you can and that's actually the process I ended up implementing in the end. I was having trouble getting the file path from the image on the Android phone that would allow me to do that. This is the answer that helped: stackoverflow.com/a/36714242/5443056

Why does an image captured using camera intent gets rotated on some de...

android image camera rotation android-camera-intent
Rectangle 27 41

In Android 4, the simplest option to receiving raw image data without displaying it on screen is to use the Camera.setPreviewTexture() call to route the preview frames to the GPU.

You can use this in two ways:

  • Do your actual processing on the GPU: Set up an OpenGL context (OpenGL ES 2 tutorial), and create a SurfaceTexture object in that context. Then pass that object to setPreviewTexture, and start preview. Then, in your OpenGL code, you can call SurfaceTexture.updateTexImage, and the texture ID associated with the SurfaceTexture will be updated to the latest preview frame from the camera. You can also read back the RGB texture data to the CPU for further processing using glReadPixels, if desired.
  • Do your processing on the CPU: You can simply create a dummy SurfaceTexture object without any OpenGL context set up. Pass any integer you want as the texture ID, and connect the SurfaceTexture to the camera using setPreviewTexture. As long as you don't call updateTexImage, the SurfaceTexture will simply discard all data passed into it by the camera. Then set up preview callbacks using setPreviewCallback, and use that data (typically in a YUV format) for CPU processing. This is probably less efficient than #1, but does not require knowing OpenGL.

Has anyone come across a simple example of using glReadPixels after SurfaceTexture.updateTexImage returns?

The Method 2 does not work for Nexus 4.

glReadPixels()

Android SDK: Get raw preview camera image without displaying it - Stac...

android
Rectangle 27 23

In a nutshell, you can do a camera preview in full screen however you'll need to find out the appropriate sizes among the supported preview sizes by yourself, only if a customized camera preview is what you want.

If you want to set a specific size for your camera preview, set this in the surfaceChanged() method as noted in the comments above. When setting preview size, you must use values from getSupportedPreviewSizes(). Do not set arbitrary values in the setPreviewSize() method.

It seemed you can't manually pass the size you want other than the sizes provides by getSupportedPreviewSizes(). With a closer examine the sizes supported by your phones camera, you'll find the ratio of sizes supported might not exactly the same as your screen's ratio.

For example, Samsung Galaxy Ace II has 480x800 resolution screen, by reading the Size returned from getSupportedPreviewSizes(), its camera supports:

and if you want to display your camera preview in full screen correctly (without stretch), you'll need to calculate, compare and apply the suitable ratio in these supported preview sizes.

Implementation of finding a proper preview size is not that complicated stuff. A common method for doing this would be something like this:

/**
     * Calculate the optimal size of camera preview
     * @param sizes
     * @param w
     * @param h
     * @return
     */
    private Size getOptimalSize(List<Size> sizes, int w, int h) {

        final double ASPECT_TOLERANCE = 0.2;        
        double targetRatio = (double) w / h;         
        if (sizes == null)             
            return null;          
        Size optimalSize = null;         
        double minDiff = Double.MAX_VALUE;          
        int targetHeight = h;          
        // Try to find an size match aspect ratio and size         
        for (Size size : sizes) 
        {             
//          Log.d("CameraActivity", "Checking size " + size.width + "w " + size.height + "h");            
            double ratio = (double) size.width / size.height;            
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)                
                continue;             
            if (Math.abs(size.height - targetHeight) < minDiff) 
            {                 
                optimalSize = size;                 
                minDiff = Math.abs(size.height - targetHeight);             
            }         
        }          
        // Cannot find the one match the aspect ratio, ignore the requirement     

        if (optimalSize == null)
        {
            minDiff = Double.MAX_VALUE;             
            for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff)
                {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight); 
                }
            }
        }

        SharedPreferences previewSizePref;
        if (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
            previewSizePref = getSharedPreferences("PREVIEW_PREF",MODE_PRIVATE);
        } else {
            previewSizePref = getSharedPreferences("FRONT_PREVIEW_PREF",MODE_PRIVATE);
        }

        SharedPreferences.Editor prefEditor = previewSizePref.edit();
        prefEditor.putInt("width", optimalSize.width);
        prefEditor.putInt("height", optimalSize.height);

        prefEditor.commit();

//      Log.d("CameraActivity", "Using size: " + optimalSize.width + "w " + optimalSize.height + "h");            
        return optimalSize;     
    }

And you can also do the similar to find out the suitable camera sizes (the output picture size).

Note: I found the original version of the code above from Internet and I did some modification/optimisation for my own purpose.

First, Thanks a lot for your answer. I've updated the question in order to respond to your answer for a better visibility. My application is using more front camera than back camera.Seems that, if native camera does not display front camera in fullscreen (at least not on a S2 and S3 phone) because of aspect ratio issue, I will not be able to do the same without distorting the image...

I am using samsung s7 camera preview showing only half of the screen.

android - Camera display / preview in full screen does not maintain as...

android android-camera
Rectangle 27 202

You use the UIImageWriteToSavedPhotosAlbum() function.

//Let's say the image you want to save is in a UIImage called "imageToBeSaved"
UIImageWriteToSavedPhotosAlbum(imageToBeSaved, nil, nil, nil);
//ViewController.m
- (IBAction)onClickSavePhoto:(id)sender{

    UIImageWriteToSavedPhotosAlbum(imageToBeSaved, nil, nil, nil);
}

Let's say I have '- (IBAction)onClickSavePhoto:(id)sender;' in my ViewController.h file, using what you have above, what exactly would I need to place in the ViewController.m file? Thanks again so much!

@user1470914 See my edit. Also, where are you getting the image to be saved to the camera roll? Is it already in your app's bundle, or does the user take a picture and then you save it to the camera roll?

Thanks for your patience qegal. I haven't had a chance to revisit this issue until now. Your EDIT us super helpful. The image is in the app's bundle. There are several images in the app and they can be viewed as small thumbnails. When a small thumbnail is selected it goes to a new view and a fullscreen version can be viewed. I have a button in the right corner of the top nav that says "save" and this is the button that I wish to save the image to the device's cameral roll so that it may be applied as a wallpaper. Thanks again for your help and patience (not sure why casperOne closed this).

I also added UIImageView *imageToBeSaved; to my .h file. I thought that I would have to add @synthesize imageToBeSaved in my .m but I get an error that says "missing context for property implementation declaration"

From iOS10 on, using NSPhotoLibraryUsageDescription key in plist is mandatory. Otherwhise the app crashes.

iphone - How can I save an image to the camera roll? - Stack Overflow

iphone ios objective-c ipad camera
Rectangle 27 9

You need to read up about the Camera. (I think to do what you want, you'd have to save the current image to your app, do the select/delete there, and then recall the camera to try again, rather than doing the retry directly inside the camera.)

android - Capture Image from Camera and Display in Activity - Stack Ov...

android image camera capture
Rectangle 27 9

You need to read up about the Camera. (I think to do what you want, you'd have to save the current image to your app, do the select/delete there, and then recall the camera to try again, rather than doing the retry directly inside the camera.)

android - Capture Image from Camera and Display in Activity - Stack Ov...

android image camera capture
Rectangle 27 7

The problem was that image rotation was added to the photo as EXIF data not used by most browsers. There are two solutions:

Apply the rotation on the server side. I was using the Ruby plugin Paperclip (by Thoughtbot) and just had to include the auto-orient convert option to the has_attached_file command in the model:

Rotate the photo within the iPhone app. This was solved in another stackoverflow question; calling the scaleAndRotate method replaces the rotation meta-data with an image transform, thanks to @Squeegy.

uiimagepickercontroller - iPhone camera images are rotated when upload...

iphone uiimagepickercontroller image-uploading
Rectangle 27 21

It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.

Request this permission on the AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Activity
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;

Then fire this Intent in an onClick:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
    // Create the File where the photo should go
    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // Error occurred while creating the File
        Log.i(TAG, "IOException");
    }
    // Continue only if the File was successfully created
    if (photoFile != null) {
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }
}

Add the following support method:

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",         // suffix
            storageDir      // directory
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        try {
            mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
            mImageView.setImageBitmap(mImageBitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath))
FileNotFoundException

"Uri.parse(mCurrentPhotoPath))" is the solution since MediaStore.EXTRA_OUTPUT leads to null intent result.

My picture is coming in landscape mode by default, am I missing anything?

I am using this in a FragmentDialog and it crashes on this line: startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE); with this error:java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE flg=0x3 cmp=com.lge.camera/.app.CameraActivity clip={text/uri-list U:file:///storage/emulated/0/Pictures/JPEG_20170721_040943_-644534083.jpg} (has extras) } from ProcessRecord{65edf85 19134:com.devhopes.ryde/u0a151} (pid=19134, uid=10151) with revoked permission android.permission.CAMERA - when I click on the image view

@LizG you need to request permissions to use the camera on Android 6.0 and above.

@AlbertVilaCalvo other than adding them to AndroidManifest, how can I do that?

android - Capture Image from Camera and Display in Activity - Stack Ov...

android image camera capture