You are on page 1of 8

Camera,

usar la cmara
Multimedia
A.

para fotos

Curso Intersemestral, ENE 2016


Tecnolgico Nacional de Mxico, Instituto Tecnolgico de Ciudad Madero
Instructores : Ana Guadalupe Vlez Chong,
Nelson Rangel Valdez

Objetivo: Conocer el como utilizar los recursos


fsicos(hardware) del dispositivo mvil que en este caso es la
cmara fotogrfica, pudiendo tomar fotografas y almacenarlas
en el dispositivo.

activity_main.xml
Nuestra interfaz estar
compuesta de un solo botn, el
cdigo XML es el siguiente:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnTomaFoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="@string/strTomaFoto" />
</RelativeLayout>

Crear un string para el texto del


botn:
<string name="strTomaFoto">Toma Foto</string>

ActivityMain.java
public class MainActivity extends ActionBarActivity {
private final String ruta_fotos = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/misfotos/";
private File file = new File(ruta_fotos);
private Button boton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//======== codigo nuevo ========
boton = (Button) findViewById(R.id.btnTomaFoto);
//Si no existe crea la carpeta donde se guardaran las fotos
file.mkdirs();
//accion para el boton
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String file = ruta_fotos + getCode() + ".jpg";
File mi_foto = new File( file );
try {
mi_foto.createNewFile();
} catch (IOException ex) {
Log.e("ERROR ", "Error:" + ex);
}
//
Uri uri = Uri.fromFile(mi_foto);
//Abre la camara para tomar la foto
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Guarda imagen
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//Retorna a la actividad
startActivityForResult(cameraIntent, 0);
}
});
//====== codigo nuevo:end ======
}

Creamos una variable ruta_fotos tipo


String, la cual almacenara la direccin en la
cual nuestra foto se almacenara, nuestra ruta
es sdcard/pictures/misfotos/.
A continuacin creamos un archivo tipo File y le
enviamos como parmetro la ruta donde se
guardara la foto.

private final String ruta_fotos = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/misfotos/";


private File file = new File(ruta_fotos);
private Button boton;

En la accin del botn se aade el


cdigo para tomar y guardar la
foto.

//accin para el botn


boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String file = ruta_fotos + getCode() + ".jpg";
File mi_foto = new File( file );
try {
mi_foto.createNewFile();
} catch (IOException ex) {
Log.e("ERROR ", "Error:" + ex);
}

Cuando se presione el botn, se


abrir la cmara del celular para
tomar la foto, cuando esta accin
se realice, se volver a la
aplicacin.

Uri uri = Uri.fromFile(mi_foto);


//Abre la camara para tomar la foto
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Guarda imagen
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//Retorna a la actividad
startActivityForResult(cameraIntent, 0);
}
});

Para guardar las fotos, se necesitan de unnombre


nicopara eso se crea un mtodo que har uso de
la hora y fecha del dispositivo para generar un
cdigo nico pic_yyyymmddhhmmss.jpgque
nos sirve de nombre de imagen.
/**@return photoCode**/
@SuppressLint("SimpleDateFormat")
private String getCode()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date() );
String photoCode = "pic_" + date;
return photoCode;
}

Permisos
Estos se agregan en el
AndroidManifest.xml, te permiten
manipular la cmara desde la aplicacin
y escribir en elsdcard.

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

You might also like