您好,登錄后才能下訂單哦!
這篇文章給大家介紹Android應用如何獲取相冊中的圖片,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
容易出錯的地方:
1、當我們指定了照片的uri路徑,我們就不能通過data.getData();來獲取uri,而應該直接拿到uri(用全局變量或者其他方式)然后設置給imageView
imageView.setImageURI(uri);
2、我發現手機前置攝像頭拍出來的照片只有幾百KB,直接用imageView.setImageURI(uri);沒有很大問題,但是后置攝像頭拍出來的照片比較大,這個時候使用imageView.setImageURI(uri);就容易出現 out of memory(oom)錯誤,我們需要先把URI轉換為Bitmap,再壓縮bitmap,然后通過imageView.setImageBitmap(bitmap);來顯示圖片。
3、將照片存放到SD卡中后,照片不能立即出現在系統相冊中,因此我們需要發送廣播去提醒相冊更新照片。
4、這里用到了sharepreference,要注意用完之后移除緩存。
代碼:
MainActivity:
package com.sctu.edu.test; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.sctu.edu.test.tools.ImageTools; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { private static final int PHOTO_FROM_GALLERY = 1; private static final int PHOTO_FROM_CAMERA = 2; private ImageView imageView; private File appDir; private Uri uriForCamera; private Date date; private String str = ""; private SharePreference sharePreference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Android不推薦使用全局變量,我在這里使用了sharePreference sharePreference = SharePreference.getInstance(this); imageView = (ImageView) findViewById(R.id.imageView); } //從相冊取圖片 public void gallery(View view) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, PHOTO_FROM_GALLERY); } //拍照取圖片 public void camera(View view) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); uriForCamera = Uri.fromFile(createImageStoragePath()); sharePreference.setCache("uri", String.valueOf(uriForCamera)); /** * 指定了uri路徑,startActivityForResult不返回intent, * 所以在onActivityResult()中不能通過data.getData()獲取到uri; */ intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForCamera); startActivityForResult(intent, PHOTO_FROM_CAMERA); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //第一層switch switch (requestCode) { case PHOTO_FROM_GALLERY: //第二層switch switch (resultCode) { case RESULT_OK: if (data != null) { Uri uri = data.getData(); imageView.setImageURI(uri); } break; case RESULT_CANCELED: break; } break; case PHOTO_FROM_CAMERA: if (resultCode == RESULT_OK) { Uri uri = Uri.parse(sharePreference.getString("uri")); updateDCIM(uri); try { //把URI轉換為Bitmap,并將bitmap壓縮,防止OOM(out of memory) Bitmap bitmap = ImageTools.getBitmapFromUri(uri, this); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } removeCache("uri"); } else { Log.e("result", "is not ok" + resultCode); } break; default: break; } } /** * 設置相片存放路徑,先將照片存放到SD卡中,再操作 * * @return */ private File createImageStoragePath() { if (hasSdcard()) { appDir = new File("/sdcard/testImage/"); if (!appDir.exists()) { appDir.mkdirs(); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); date = new Date(); str = simpleDateFormat.format(date); String fileName = str + ".jpg"; File file = new File(appDir, fileName); return file; } else { Log.e("sd", "is not load"); return null; } } /** * 將照片插入系統相冊,提醒相冊更新 * * @param uri */ private void updateDCIM(Uri uri) { Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(uri); this.sendBroadcast(intent); Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath()); MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", ""); } /** * 判斷SD卡是否可用 * * @return */ private boolean hasSdcard() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } /** * 移除緩存 * * @param cache */ private void removeCache(String cache) { if (sharePreference.ifHaveShare(cache)) { sharePreference.removeOneCache(cache); } else { Log.e("this cache", "is not exist."); } } }
ImageTools:
package com.sctu.edu.test.tools; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class ImageTools { /** * 通過uri獲取圖片并進行壓縮 * * @param uri * @param activity * @return * @throws IOException */ public static Bitmap getBitmapFromUri(Uri uri, Activity activity) throws IOException { InputStream inputStream = activity.getContentResolver().openInputStream(uri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inDither = true; options.inPreferredConfig = Bitmap.Config.ARGB_8888; BitmapFactory.decodeStream(inputStream, null, options); inputStream.close(); int originalWidth = options.outWidth; int originalHeight = options.outHeight; if (originalWidth == -1 || originalHeight == -1) { return null; } float height = 800f; float width = 480f; int be = 1; //be=1表示不縮放 if (originalWidth > originalHeight && originalWidth > width) { be = (int) (originalWidth / width); } else if (originalWidth < originalHeight && originalHeight > height) { be = (int) (originalHeight / height); } if (be <= 0) { be = 1; } BitmapFactory.Options bitmapOptinos = new BitmapFactory.Options(); bitmapOptinos.inSampleSize = be; bitmapOptinos.inDither = true; bitmapOptinos.inPreferredConfig = Bitmap.Config.ARGB_8888; inputStream = activity.getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, bitmapOptinos); inputStream.close(); return compressImage(bitmap); } /** * 質量壓縮方法 * * @param bitmap * @return */ public static Bitmap compressImage(Bitmap bitmap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); int options = 100; while (byteArrayOutputStream.toByteArray().length / 1024 > 100) { byteArrayOutputStream.reset(); //第一個參數 :圖片格式 ,第二個參數: 圖片質量,100為最高,0為最差 ,第三個參數:保存壓縮后的數據的流 bitmap.compress(Bitmap.CompressFormat.JPEG, options, byteArrayOutputStream); options -= 10; } ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); Bitmap bitmapImage = BitmapFactory.decodeStream(byteArrayInputStream, null, null); return bitmapImage; } }
AndroidMainfest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest package="com.sctu.edu.test" xmlns:android="http://schemas.android.com/apk/res/android"> <uses-feature android:name="android.hardware.camera" android:required="true" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses-permission android:name="com.miui.whetstone.permission.ACCESS_PROVIDER"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-feature android:name="android.hardware.camera.autofocus" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:background="#fff" android:orientation="vertical" tools:context="com.sctu.edu.test.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="從圖庫找圖片" android:id="@+id/gallery" android:onClick="gallery" android:background="#ccc" android:textSize="20sp" android:padding="10dp" android:layout_marginLeft="30dp" android:layout_marginTop="40dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="拍照獲取圖片" android:id="@+id/camera" android:onClick="camera" android:background="#ccc" android:textSize="20sp" android:padding="10dp" android:layout_marginLeft="30dp" android:layout_marginTop="40dp" /> <ImageView android:layout_width="300dp" android:layout_height="300dp" android:id="@+id/imageView" android:scaleType="fitXY" android:background="@mipmap/ic_launcher" android:layout_marginTop="40dp" android:layout_marginLeft="30dp" /> </LinearLayout>
關于Android應用如何獲取相冊中的圖片就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。