사악미소
현대마법의 공방
사악미소
전체 방문자
오늘
어제
  • 분류 전체보기
    • Document
    • JavaScript
    • jQuery
    • Spring Web
      • Spring Framework
      • Spring Boot
    • Android
      • Java Code
      • Setting
    • iOS
      • Swift Code
      • Setting
    • PHP
      • Code
      • Setting
    • AWS
    • LINUX
      • Rocky Linux
      • CentOS
    • Node.js
    • Developer Tool
    • GIT
    • MAC
    • Scraping Document
    • MariaDB
    • WYSIWYG
    • Scouter
    • Docker
    • Planning
    • 용어정리
반응형

인기 글

최근 댓글

Programmer 사악미소.
사악미소

사악미소의 현대마법의 공방

[Android] 갤러리 이미지 가져오기 및 썸네일 생성
Android/Java Code

[Android] 갤러리 이미지 가져오기 및 썸네일 생성

2022. 11. 10. 14:26
728x90

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="imgSize">240dp</dimen>
</resources>

 

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;

import org.example.galleryfileprovider.databinding.ActivityMainBinding;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    String filePath = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        ActivityResultLauncher<Intent> galleryLauncher = registerForActivityResult(
              new ActivityResultContracts.StartActivityForResult()
            , new ActivityResultCallback<ActivityResult>()
        {
            @Override
            public void onActivityResult(ActivityResult result) {
                int calRatio = calculateInSampleSize(
                      result.getData().getData()
                    , getResources().getDimensionPixelSize(R.dimen.imgSize)
                    , getResources().getDimensionPixelSize(R.dimen.imgSize)
                );

                BitmapFactory.Options option = new BitmapFactory.Options();
                option.inSampleSize = calRatio;

                try {
                    InputStream inputStream = getContentResolver().openInputStream(result.getData().getData());
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, option);
                    inputStream.close();
                    if(bitmap != null) {
                        binding.imgThumbnail.setImageBitmap(bitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        binding.btnGallery.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                galleryLauncher.launch(intent);
            }
        });
    }

    private int calculateInSampleSize(Uri fileUri, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        try {
            InputStream inputStream = getContentResolver().openInputStream(fileUri);

            // inJustDecodeBounds 값을 true 로 설정한 상태에서 decodeXXX() 를 호출.
            // 로딩 하고자 하는 이미지의 각종 정보가 options 에 설정 된다.
            BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 비율 계산
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;

        //inSampleSize 비율 계산
        if (height > reqHeight || width > reqWidth) {

            int halfHeight = height / 2;
            int halfWidth = width / 2;

            while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }
}

 

 

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imgThumbnail"
        android:layout_width="240dp"
        android:layout_height="240dp"
        android:layout_marginTop="80dp"
        android:layout_weight="1"
        android:src="@drawable/user_thumbnail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
    />

    <Button
        android:id="@+id/btnGallery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="갤러리"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imgThumbnail"
        tools:ignore="MissingConstraints"
    />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

 

728x90

'Android > Java Code' 카테고리의 다른 글

[Android] FCM 메시지 송수신 Application 제작  (0) 2023.02.01
[Android] Activity에서 Dark Theme 비활성화기  (0) 2023.01.04
[Android] 카메라 사진 가져오기 및 썸네일 생성  (0) 2022.11.10
[Android] setOnClickListener(this)를 이용한 버튼 클릭 이벤트  (0) 2022.11.09
[Android] Application 설치 여부 및 확인  (0) 2022.08.05
    'Android/Java Code' 카테고리의 다른 글
    • [Android] FCM 메시지 송수신 Application 제작
    • [Android] Activity에서 Dark Theme 비활성화기
    • [Android] 카메라 사진 가져오기 및 썸네일 생성
    • [Android] setOnClickListener(this)를 이용한 버튼 클릭 이벤트
    사악미소
    사악미소

    티스토리툴바