Android - Trabalhando com imagens
De Aulas
Links relacionados: Dispositivos Móveis
activity_main.xml
1<?xml version="1.0" encoding="utf-8"?>
2<android.support.constraint.ConstraintLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 tools:context="com.saulopz.mygetimages.MainActivity">
9
10 <ImageView
11 android:id="@+id/image"
12 android:layout_width="match_parent"
13 android:layout_height="0dp"
14 android:layout_marginBottom="8dp"
15 android:layout_marginEnd="8dp"
16 android:layout_marginStart="8dp"
17 android:layout_marginTop="8dp"
18 android:contentDescription="@string/todo"
19 app:layout_constraintBottom_toBottomOf="parent"
20 app:layout_constraintEnd_toEndOf="parent"
21 app:layout_constraintLeft_toLeftOf="parent"
22 app:layout_constraintRight_toRightOf="parent"
23 app:layout_constraintStart_toStartOf="parent"
24 app:layout_constraintTop_toBottomOf="@+id/button"
25 app:srcCompat="@mipmap/ic_launcher" />
26
27 <Button
28 android:id="@+id/button"
29 android:layout_width="wrap_content"
30 android:layout_height="wrap_content"
31 android:layout_marginEnd="8dp"
32 android:layout_marginStart="8dp"
33 android:layout_marginTop="8dp"
34 android:text="Foto"
35 app:layout_constraintEnd_toEndOf="parent"
36 app:layout_constraintStart_toStartOf="parent"
37 app:layout_constraintTop_toTopOf="parent" />
38
39</android.support.constraint.ConstraintLayout>
AndroidManifest.xml
Adicionar as seguintes linhas antes de <application
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
MainActivity.java
1package com.saulopz.mygetimages;
2
3import android.app.AlertDialog;
4import android.content.Intent;
5import android.database.Cursor;
6import android.graphics.Bitmap;
7import android.graphics.BitmapFactory;
8import android.net.Uri;
9import android.os.Bundle;
10import android.provider.MediaStore;
11import android.support.v7.app.AppCompatActivity;
12import android.view.View;
13import android.widget.ImageView;
14
15import java.io.BufferedInputStream;
16import java.io.ByteArrayOutputStream;
17import java.io.File;
18import java.io.FileOutputStream;
19import java.io.IOException;
20import java.io.InputStream;
21import java.net.URL;
22
23public class MainActivity extends AppCompatActivity {
24 private static final int SELECT_PHOTO = 12345;
25 private String filename = "/userimage.jpg";
26 private ImageView imagePick;
27 static final int REQUEST_IMAGE_CAPTURE = 1;
28
29
30 @Override
31 protected void onCreate(Bundle savedInstanceState) {
32 super.onCreate(savedInstanceState);
33 setContentView(R.layout.activity_main);
34 imagePick = findViewById(R.id.image);
35 imagePick.setOnClickListener(new View.OnClickListener() {
36 @Override
37 public void onClick(View v) {
38 Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
39 photoPickerIntent.setType("image/*");
40 startActivityForResult(photoPickerIntent, SELECT_PHOTO);
41 }
42 });
43 findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
44 @Override
45 public void onClick(View v) {
46 takeAPicture();
47 }
48 });
49 setImage();
50 }
51
52 @Override
53 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
54 boolean ok = false;
55 super.onActivityResult(requestCode, resultCode, data);
56 try {
57 String imagePath;
58 if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
59 Uri pickedImage = data.getData();
60 String[] filePath = {MediaStore.Images.Media.DATA};
61 Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
62 cursor.moveToFirst();
63 imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
64 // If is on internet, then download.
65 if (imagePath.contains("http")) {
66 downloadUserImage(imagePath);
67 }
68 Bitmap bitmap = null;
69 try {
70 BitmapFactory.Options options = new BitmapFactory.Options();
71 options.inPreferredConfig = Bitmap.Config.ARGB_8888;
72 bitmap = BitmapFactory.decodeFile(imagePath, options);
73 } catch (OutOfMemoryError outOfMemoryError) {
74 dialog("Erro de memória", outOfMemoryError.getMessage());
75 }
76 if (bitmap == null) {
77 Uri selectedImage = data.getData();
78 if (selectedImage != null) {
79 InputStream imageStream = getContentResolver().openInputStream(selectedImage);
80 bitmap = BitmapFactory.decodeStream(imageStream);
81 }
82 }
83 if (bitmap != null) {
84 int size = bitmap.getWidth() < bitmap.getHeight() ? bitmap.getWidth() : bitmap.getHeight();
85 Bitmap bitmapCrop = Bitmap.createBitmap(bitmap, 0, 0, size, size);
86 Bitmap userPic = Bitmap.createScaledBitmap(bitmapCrop, 300, 300, false);
87
88 saveImage(userPic);
89 setImage();
90 } else {
91 dialog("Erro de carregamento", "Não foi possível carregar" +
92 " a imagem escolhida " + imagePath);
93 }
94 } else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
95 Bundle extras = data.getExtras();
96 Bitmap imageBitmap = (Bitmap) extras.get("data");
97 saveImage(imageBitmap);
98 setImage();
99 }
100
101 } catch (Exception e) {
102 dialog("ERRO", e.getMessage());
103 }
104 }
105
106 void downloadUserImage(String link) {
107 try {
108 URL url = new URL(link);
109 InputStream in = new BufferedInputStream(url.openStream());
110 ByteArrayOutputStream out = new ByteArrayOutputStream();
111 byte[] buf = new byte[1024];
112 int n;
113 while (-1 != (n = in.read(buf))) {
114 out.write(buf, 0, n);
115 }
116 out.close();
117 in.close();
118 byte[] response = out.toByteArray();
119
120 String filePath = this.getFilesDir().getPath() + filename;
121 FileOutputStream fos = new FileOutputStream(filePath);
122 fos.write(response);
123 fos.close();
124 } catch (Exception e) {
125 e.printStackTrace();
126 }
127 }
128
129 void setImage() {
130 String filePath = getFilesDir().getPath() + filename;
131 File imgFile = new File(filePath);
132 if (imgFile.exists()) {
133 Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
134 imagePick.setImageBitmap(myBitmap);
135 }
136 }
137
138 private void takeAPicture() {
139 Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
140 if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
141 startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
142 }
143 }
144
145 void saveImage(Bitmap bmp) {
146 try {
147 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
148 bmp.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
149 String filePath = getFilesDir().getPath() + filename;
150 File f = new File(filePath);
151 FileOutputStream fo = new FileOutputStream(f);
152 fo.write(bytes.toByteArray());
153 fo.close();
154 } catch (IOException e) {
155 dialog("ERRO", e.getMessage());
156 }
157 }
158
159 void dialog(String title, String content) {
160 AlertDialog.Builder builder = new AlertDialog.Builder(this);
161 builder.setTitle(title);
162 builder.setMessage(content);
163 builder.setNeutralButton("OK", null);
164 builder.show();
165 }
166}