Get image from camera android

У нас есть фотик и котик — работаем с камерой

Практически все современные телефоны и планшеты снабжаются камерами, что позволяет фотографировать любимых котиков.

Сначала сделаем небольшие приготовления. Есть класс устройств, у которых нет камер, например, электронные ридеры. Чтобы пользователи этих устройств не скачивали зря ваше приложение, которое окажется для них бесполезным, пропишем в манифесте требование наличия камеры.

Если камера в вашем приложении выполняет вспомогательную функцию, а приложение может работать и без неё, то установите значение false в предыдущем коде и проверяйте наличие камеры программно. Если камеры нет, то отключайте возможность съёмок для пользователя.

Программное включение приложения Камера

Раньше на старых телефонах можно было программно запустить из своей программы системное приложение «Камера» (в этом случае вам не понадобятся дополнительные разрешения) через намерение.

Особого смысла в этом нет, так как результат не возвращается в приложение. Но вполне подходило для быстрого запуска камеры. Впрочем, сейчас этот код может и не сработать.

А вообще у пользователя могут стоять разные приложения, способные фотографировать. Тогда у вас будет появляться диалоговое окно с выбором нужного приложения. Они все имеют в своём составе такую запись в манифесте (для общего развития):

У Гугла есть своя программа Google Камера. Запустим её, зная имя пакета.

При вызове метода getIntent() вместо new Intent() приложение запускалось сразу, иначе — выводилось диалоговое окно выбора программы из списка. Также нужно быть уверенным, что программа установлена, в примере нет кода проверки.

Делаем фотографии и сохраняем результат. Простой пример

Просто включить камеру не слишком интересно. Рассмотрим практичный пример, когда мы программно запустим приложение «Камера», а полученную фотографию сохраним в папке. Сначала сделаем простой вариант, а потом напишем более сложное приложение.

Используйте статическую константу MediaStore.ACTION_IMAGE_CAPTURE для создания намерения, которое потом нужно передать методу startActivityForResult(). Разместите на форме кнопку и ImageView, в который будем помещать полученный снимок. Этот код запускает стандартное приложение камеры. Полученное с камеры изображение можно обработать в методе onActivityResult():

Не включайте в манифест разрешение на работу с камерой, иначе получите крах приложения.

Данный код запустит приложение, работающее с камерой, позволяя пользователю поменять настройки изображения, что освобождает вас от необходимости создавать своё собственное приложение для этих нужд. Вполне возможно, что у вас будет несколько приложений, умеющих делать фотографии, тогда сначала появится окно выбора программы.

При тестировании примера на своём телефоне я обнаружил небольшую проблему — когда снимок передавался обратно на моё приложение, то оно находилось в альбомном режиме, а потом возвращалось в портретный режим. При этом полученный снимок терялся. Поэтому перед нажатием кнопки я поворачивал телефон в альбомный режим, чтобы пример работал корректно. Возможно следует предусмотреть подобное поведение, например, запретить приложению реагировать на поворот и таким образом избежать перезапуска Activity. У некоторых телефонов такой проблемы нет.

По умолчанию фотография возвращается в виде объекта Bitmap, содержащего миниатюру. Этот объект находится в параметре data, передаваемом в метод onActivityResult(). Чтобы получить миниатюру в виде объекта Bitmap, нужно вызвать метод getParcelableExtra() из намерения, передав ему строковое значение data. В примере использовался упрощённый вариант.

Миниатюра и полноразмерное изображение

Если вы укажете исходящий путь URI с помощью параметра MediaStore.EXTRA_OUTPUT в запущенном намерении, полноразмерное изображение, снятое камерой, сохранится в заданном месте. В таком случае в метод onActivityResult() не будет передана миниатюра, а итоговое намерение продемонстрирует значение null.

В следующем примере показано, как при создании снимка получать миниатюру или полноценное изображение, используя намерение. Изображение будет сохранено во внешнем хранилище под именем test.jpg.

Пример работает на устройствах до Android 6.0, потом появились различные системные ограничения и нужно писать дополнительный код.

Читайте также:  Videobox для android последняя версия

Добавим разрешение на запись файла в хранилище.

В реальных приложениях для создания имён файлов используют текущую дату, чтобы обеспечить уникальность и не затереть существующую фотографию.

Запуск камеры в нужном режиме

Мы можем выбрать намерение, позволяющее включить камеру в нужном режиме: фотосъёмка или видео.

Снимаем и кадрируем

Рассмотрим ещё один пример с режимом кадрирования. Основная часть кода остаётся прежней. Рекомендую проверять работу с камерой на реальных устройствах, так как многие производители заменяют стандартные методы съёмки своими прошивками и драйверами. В частности, намерение с кадрированием является проблемной, и в интернете многие жалуются на отсутствие поддержки этого способа. Пример для старых устройств до Android 6.0.

Создадим простенький макет из кнопки для запуска камеры и ImageView для вывода кадрированного изображения.

Для большей красоты сделаем задний фон у ImageView с закруглёнными углами и обводкой. Для этого в атрибуте android:background мы прописали специальный стиль. Создайте папку res/drawable, а в ней файл background.xml следующего содержания:

Этот шаг не является обязательным и его можно пропустить.

При нажатии кнопки запускаем приложение Камера и ожидаем результата.

После того, как пользователь сделал нужный кадр, программа Камера возвращает результат обратно в наше приложение. Результат обрабатывается в методе onActivityResult():

Получив полноразмерное изображение, мы пытаемся откадрировать его. Для этого создадим метод performCrop(), который запускает специальное намерение, предназначенное для этих целей. В успешном случае результат снова возвращается в наше приложение, но уже с другим кодом PIC_CROP. Теперь мы имеем нужное изображение, которое можно вывести на экран.

При кадрировании мы указываем желаемые размеры (код метода ниже). Если указать слишком больше размеры (больше 400), то результат не возвращается. Попробуйте добавить ещё два параметра:

Результат работы приложения, когда запускается намерение кадрирования и итоговый результат. Желательно тренироваться на кошках.

Источник

With respect to an Android novice, to test things out, you would require a straightforward and clear guide. As you can discover, there are numerous articles, sites, and aides on this subject. However, a large portion of them is not working as well as haven’t tried or too complex to even think about understanding. Let me take you through a guide on the most proficient method to execute this without any problem.

you can download the full source code from Github.

First, you must have a ImageView in your layout implemented to capture the image you upload either through the camera or Gallery.

Following is my ImageView implementation for the above purpose.

Now, after doing this your activity_main.xml will look like this.

Now in the MainActivity class, you have to declare the ImageView first.

In the onCreate override method, you have to initialize the ImageView element by adding the following,

RUN-Time Permission for Camera and External Storage

as you aware that if you are working with marshmallow or above version device then you need to take first run time permission. for our app, we will require two run time permission.

  1. Camera Permission
  2. External Storage Permission

So let’s see how you will get this permission

first you need to define this two permission in your manifest file ie. AndroidManifest.xml

Now, your AndroidManifest.xml will look like this:

Okay after adding this two permission on the manifest file you need to make a function to check runtime permission on MainActivity. This function will show a popup if the user doesn’t have permission so that the user can click on the allow button to grant permission to your APP.

Now you need to Override onRequestPermissionsResult where you will handle your permission result. if permission granted then you can proceed to call chooseImage function.

Now let’s see chooseImage function, which will show a dialog with three option

  1. Take Photo
  2. choose a photo from the gallery
  3. Exit

Now to handle the result of your startActivityForResult, you need to override onActivityResult

Once you are done with all of the steps, then you call the permission check function in the onCreate method.

So after doing all of the things your MainActivity.java will look like this

Читайте также:  Громкий звонок для android

That’s it, now you can run your app and enjoy the code.

I hope you enjoy this tutorial and you have learned how to get images from the gallery or capture images from the camera on Android.

Источник

Android — Get camera thumbnail and full image

Feb 17, 2018 · 5 min read

Hello, My name is Rodrigo and i’m a mobile developer, today i i’ll teach you how to get images from android camera, there are two ways to get one picture from the native camera app from your device, get an thumbnail, small picture with low resolution just to show to user in tiny image view, and the full image resolution.

Fun fact, why you can’t use aways the fu l l resolution image, well there are some problems around that, think in this situation, you get the full-sized image from the camera and you need to show in a another fullscreen activity this image, imagine you transfer one image 1080p or something better, to another activity by the intent, probably you will receive an exception OutOfMemmoryError (One of various exceptions) because android can’t handle large files like this, this is why exists the thumbnail, it is a tiny bitmap which you can handle and transfer like you wish.

You don’t need to get angry anymore when you can’t get one good resolution picture or even one picture of the camera, i already pass by a lot of problems with the Android camera and this is a good solution which i found to fix this.

Getting a thumbnail

First in your activity or fragment when you request a picture from camera you need to do this

You will call a intent passing ACTION_IMAGE_CAPTURE to call the camera, obviously you need to handle the Android permissions before this, otherwise the app will crash. I use the TAKE_PICTURE with the value 1, this variable is the request code, you will need him in onActivityResult method to catch the image.

Now you can implement the method onActivityResult like this

Well let’s explain this, i use the switch to verify which case is, if the case is TAKE_PICTURE we need to check, only for safety reasons if the resultCode is RESULT_OK, this means everything work fine and the camera app give back one photo, and, also check with the intent have data, or your picture. After that you can get the bitmap and set in your imageView.

Getting the real picture

This way is more painful, but don’t worry, to get the full-sized image you need to ask the user to WRITE_EXTERNAL_STORAGE permission also. after that you need to create a fileProvider to android know where he can save the picture file, go to your Manifest and add this code:

Remember where is com.example.android, you need to change with your app package.

Now you need to create the resource telling the path to save the picture file, in the code above we use the name file_paths but you can change to one name as you wish, but remember to change in the provide you have create at Manifest:

Again you need to change com.example.package.name with the package of your app.

Ok now we can start to code, yhayy, first we need to create a file where the Android will save the picture after she was taken, ok i use the code bellow to create a random file with the name actual timeStamp, this guarantee that will never be two files with the same name:

You can use the mCurrentPhotoPath with global access just to reuse the file path after. Ok now we will create the method which will call the camera to take the picture, it’s like if you was trying to catch one thumbnail but with more things lol.

Like before you will have to pass a requestCode to catch the data after onActivityResult, i use the REQUEST_TAKE_PICTURE variable to do that. You need to check if the device have one camera to take the picture, you can do that with:

Читайте также:  Обработчик событий java android

this guarantee the app will not crash if the camera is unavailable.

Again where is com.example.android you need to change to your app package!

Remember the method we created before to generate a new file? Well here we use him, to create a new file and generate an Uri where android will save the picture. Once you have create an new Uri with the path of the file you need to add this extra in your Intent to tell to Android where he can save the picture.

ok now you just need to catch the data in onActivityResult:

Remember, if you try to catch the full-sized image android will not return the image or the url with the intent, to retrieve the image you need to use the file path you generate before.

Ok, remember the currentPhotoPath we save before well, here we use him to catch the file and generate an Uri which one we will transform in a Bitmap, if you need the file in another formats, you can easy find it on google.

Thats it. Thanks to read this post and i hope it help you. I use the Android Documentation to create the post, if you want more details about how the things work go there and enjoy.

Источник

Android Capture Image From Camera Programmatically [Updated]

Do you want to capture an image from the camera and set it into imageview or upload it to the server? then, this is the right post to learn.

The camera is a very common feature that lots of apps provide. Most of the required image capture feature in own application. eg. profile image, creating a post with an image, every food or social media app required camera feature in own application.

Basically, Image capturing is a very simple task, even if you are using custom. In this article, we are going to see how to capture images from the camera using FileProvider in your Android app.

Google introduces FileProvider in version 22.1.0. FileProvider class is a derived class from ContentProvider. In other words you can say, FileProvider provide facilitates to secure file sharing in android via content://Uri instead of a file:///Uri

checkout my other useful post:

So, Let’s start with how can we achieve capturing an image from the camera and getting the file path, and load an image in an ImageView.

Table of Contents

Step to capture image from camera programmatically

  1. Defining a FileProvider
  2. Granting Permissions to a URI, Storage & Camera
  3. Image Capture using Camera
  4. Manage Result and show image over the ImageView

1. Defining A FileProvider

Define a list of file paths for FileProvider in XML file and save it in res/xml folder. Since we want to save only in the public picture directory, we’ll just add the path of it to XML.

File Provider Location

In AndroidMenifest.xml you have to specify the FileProvider component by adding an element

Note — Replace com.example.captureimage with your package name

2. Granting Permissions To A URI, Storage & Camera

you need to add the permission in the manifest file as,

In the permission, the android:required=”true” is to tell Google’s play to filter all the Android devices which have a camera function.

If we use android:required=”false”, we need to check for the camera via programmatically.

Android 6, contains a permission system for certain tasks. Each application can request the required permission on runtime. So let’s open the Activity class add the below code for requesting runtime permission,

3. Image Capture Using Camera

Now let’s create a function to generate a random file name with .jpg extension in the external files directory.

We need to create an Image file

Create a new Intent with FileProvider URI

4. Manage Result And Show Image Over The ImageView

After action performing, we will manage the result on onActivityResult by using ResultCode and RequestCode. In onActivityResult, we have to manage three things.

  • Get actual file path or file from result intent
  • Compress a file using the FileCompressor utility
  • Finally set final output over the ImageView in Android

Источник

Оцените статью