日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android實現點擊圖片上傳SQLite數據庫_Android

作者:Awesome_lay ? 更新時間: 2022-10-07 編程語言

在使用各類App的時候,尤其是在發布朋友圈、微博的時候,都會選擇配圖,進入手機相冊,選擇自己想要的照片,作為發布內容的一部分,這里就簡單介紹一下點擊圖片上傳的方法。

1、動態獲取權限

在Android 6.0之后,除了在清單文件中聲明權限之外,通常做的還有就是動態申請權限。

//從手機相冊中獲取圖片需要動態申請權限
if(ContextCompat.checkSelfPermission(this,
? ? ? ?Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
? ? ? ? ? ActivityCompat.requestPermissions(this,
? ? ? ? ? ? ? ? ? new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},ALBUM_CODE);
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? //如果已經獲取權限,那么就直接拿
? ? ? ? ? ? ? ? ? ? takePhoto();
? ? ? ? ? ? ? ? }
//權限申請回調

? ? @Override
? ? public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
? ? ? ? switch (requestCode){
? ? ? ? ? ? case ALBUM_CODE:
? ? ? ? ? ? ? ? //獲取照片
? ? ? ? ? ? ? ? takePhoto();
? ? ? ? ? ? ? ? break;
? ? ? ? }
? ? }

2、跳轉到相冊,選擇照片

private void takePhoto() {
? ? ? ? Intent intent = new Intent(Intent.ACTION_PICK,null);
? ? ? ? intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
? ? ? ? ? ? ? ? "image/*");
? ? ? ? startActivityForResult(intent,ALBUM_CODE);
? ? }

涉及到的隱式跳轉的Action是ACTION_PICK,通過帶結果的回調startActivityForResult,將圖片信息帶回。

3、處理圖片數據,顯示在ImageView。

//從相冊返回的回調
? ? @Override
? ? protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
? ? ? ? super.onActivityResult(requestCode, resultCode, data);

? ? ? ? switch (requestCode) {
? ? ? ? ? ? case ALBUM_CODE:
? ? ? ? ? ? ? ? Uri uri = data.getData();
? ? ? ? ? ? ? ? if(uri != null){
// ? ? ? ? ? ? ? ? ? ?將圖片顯示在ImageView
? ? ? ? ? ? ? ? ? ? iv_goods.setVisibility(View.VISIBLE);
? ? ? ? ? ? ? ? ? ? //
? ? ? ? ? ? ? ? ? ? Glide.with(this).load(uri).into(iv_goods);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? break;
? ? ? ? }

將圖片顯示在ImagView中后,如果想要將圖片保存在數據庫,需要做一系列的轉換。

首先,SQLite數據庫支持的數據類型包括:int、String、text、Blob,其中Blob就是在存儲圖片等多媒體的時候,使用的類型。

其實Blob可以支持多種輸入類型,像圖片這類的資源,通常需要轉換為字節流,采用byte數組來存儲,因此在SQLite中,也可以使用byte數組來存儲圖片,因此需要將Drawable類型的圖片轉換為byte數組。

//Drawable對象轉換為byte數組
? ? public static byte[] getBytes(Drawable drawable){
? ? ? ? //將Drawable對象轉換為bitmap對象
? ? ? ? Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
? ? ? ? //創建輸出字節流
? ? ? ? ByteArrayOutputStream bos = new ByteArrayOutputStream();
? ? ? ? //壓縮
? ? ? ? bitmap.compress(Bitmap.CompressFormat.PNG, 1, bos);
? ? ? ? return bos.toByteArray();
? ? }

我這邊用的是Room組件

@ColumnInfo(name = "drawable")
? ? private byte[] drawable;

在獲取圖片資源的時候,獲取byte數組,將其轉換為Bitmap或者Drawable,就可以取出照片顯示。

?//byte數組轉換為Bitmap
? ? public static Bitmap getBitmap(byte[] bytes){
? ? ? ? //BitmapFactory
? ? ? ? Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
? ? ? ? return bitmap;
? ? }

原文鏈接:https://blog.csdn.net/qq_33235287/article/details/106128229

欄目分類
最近更新