카테고리 없음

안드로이드 /이미지/ 인텐트/ 받아서 표시하기

LODE_RUNNER 2020. 7. 9. 19:49

IMage Application.zip
0.15MB

티스토리 가입 기념 , 첫 포스팅

 

ㅡ 안드로이드/자바에서 이미지 표시하기

ㅡ 요점은 이미지 뷰 사용법이 아니라,

ㅡ 이미지 파일들을 인텐트로 요청하고 받아서

ㅡ 받은 url 정보를 해석하여

ㅡ 비트맵으로 변환하는 과정

 

ㅡ 이러한 해설은, 안드로이드 매뉴얼의 이미지 단원이나 인텐트 단원에 있지 않고

ㅡ "콘텐트 프로바이더 / 저장소 액세스 프레임워크를 사용하여 파일 열기" 해설 부분(링크)에 있슴

ㅡ 초심자가 여기까지 독학으로 오려면 몇달 걸리게 됨

 

ㅡ 소스 해설 생략  /  링크에 안내된 해설 참조 /  첨부 파일을 통째로 실행해 보세요

 

 

요점 :https://developer.android.com/guide/topics/providers/document-provider

 

 

MainActivity.java
//   MainActivity.java
//
package com.example.imageapplication;

//  import 생략

public class MainActivity extends AppCompatActivity {
    private static final int GPS_ENABLE_REQUEST_CODE = 2001;
    private static final int REQUEST_IMAGE_CAPTURE = 1 ;
    private static final int PERMISSIONS_REQUEST_CODE = 100;
    private static final int PICK_FROM_CAMERA = 0;
    private static final int PICK_FROM_ALBUM = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int GET_GALLERY_IMAGE = 200;
    private static final int REQUEST_TAKE_ALBUM = 103 ;
    private static final int  READ_REQUEST_CODE = 42;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .permitDiskReads()
                .permitDiskWrites()
                .permitNetwork().build());

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText("******** 이미지 데모 ********\n");

        Button ButtonR = (Button) findViewById(R.id.ButtonR);
        Button ButtonL = (Button) findViewById(R.id.ButtonL);

// *******************************************************************************
//   https://developer.android.com/guide/topics/providers/document-provider
        ButtonL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                final CharSequence[] SysSetUpItems =
                        {       "0 : image binary 보내기",
                                "1 : ACTION_GET_CONTENT 가져오기",
                                "2 : ACTION_OPEN_DOCUMENT 가져오기" } ;
                AlertDialog.Builder SysSetUpDialog = new AlertDialog.Builder(MainActivity.this,
                        android.R.style.Theme_DeviceDefault_Light_Dialog_Alert);
                SysSetUpDialog.setTitle("다음 중 선택하세요")
                        .setItems(SysSetUpItems, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0: //  이미지 데이타 등 바이너리 콘텐츠 보내기
                                        String uriToImage = null;
                                        Intent shareIntent2 = new Intent();
                                        shareIntent2.setAction(Intent.ACTION_SEND);
                                        shareIntent2.putExtra(Intent.EXTRA_STREAM, uriToImage);
                                        shareIntent2.setType("image/jpeg");
                                        startActivity(Intent.createChooser(shareIntent2, "abcd"));
                                        break;

                                    case 1: //
                                        // READ_REQUEST_CODE = 42;
                                        Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                                        intent1.addCategory(Intent.CATEGORY_OPENABLE);
                                        intent1.setType("image/*");
                                        startActivityForResult(intent1, 42);  // READ_REQUEST_CODE
                                        break;
                                    case 2: //
                                        // READ_REQUEST_CODE = 42;
                                        Intent intent2 = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                                        intent2.addCategory(Intent.CATEGORY_OPENABLE);
                                        intent2.setType("image/*");
                                        startActivityForResult(intent2, 42);  // READ_REQUEST_CODE
                                        break;
                                   default:
                                        break;
                                }
                            }
                        })
                        .setCancelable(true)
                        .show();
            }
        });
// *******************************************************************************
        ButtonR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                final CharSequence[] SysSetUpItems = {"0","1", "2",    "3","4","5" } ;
                AlertDialog.Builder SysSetUpDialog = new AlertDialog.Builder(MainActivity.this,
                        android.R.style.Theme_DeviceDefault_Light_Dialog_Alert);
                SysSetUpDialog.setTitle("다음 중 선택하세요")
                        .setItems(SysSetUpItems, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0: //  System.exit(0)
                                        Intent intent0 = new Intent();
                                        intent0 = new Intent(Intent.ACTION_PICK);
                                        intent0.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
                                        startActivityForResult(intent0, 1);
                                        break;
                                    case 1:
                                        Intent intent1 = new Intent();
                                        intent1.setAction(Intent.ACTION_PICK);
                                        intent1.setType("image/*");
                                        startActivityForResult(intent1, 1);
                                        break;
                                    case 2:
                                        Intent intent2 = new Intent();
                                        intent2.setAction(Intent.ACTION_GET_CONTENT);
                                        intent2.setType("image/*");
                                        startActivityForResult(intent2, 1);
                                        break;
                                    case 3:
                                        Intent intent3 = new Intent();
                                        intent3.setAction(Intent.ACTION_GET_CONTENT);
                                        intent3.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
                                        startActivityForResult(intent3, 1);
                                        break;
                                    case 4:
                                        Intent intent4 = new Intent(Intent.ACTION_PICK);
                                        intent4. setDataAndType(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                        startActivityForResult(intent4, GET_GALLERY_IMAGE);  // 200
                                        break;
                                    case 5:
                                        Intent intent5 = new Intent();
                                        intent5.setAction(Intent.ACTION_GET_CONTENT); // ACTION_PICK은 사용하지 말것, deprecated + formally
                                        intent5.setType("image/*");
                                        ((Activity)MainActivity.this).startActivityForResult(Intent.createChooser(intent5, "Get Album"), REQUEST_TAKE_ALBUM);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        })
                        .setCancelable(true)
                        .show();
            }
        });
    }
// **********************************************
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// **********************************************
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
//        Intent intent = getIntent();
//        Uri data = intent.getData();
        Log.d(" onActivityResult ", " requestCode: " + requestCode);
        switch (requestCode) {
            case 42 :   //  READ_REQUEST_CODE
                Uri uri = null;
                if (data != null) {
                    uri = data.getData();
                    Log.i("********* Image Test ********* ", "Uri: " + uri.toString());
                    try {
                        showImage(uri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                };
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + requestCode);
        }
    } ;
    public void          showImage(final Uri uri) throws IOException {
        Thread bm_thread = new Thread() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @SuppressLint("WrongViewCast")
                    @Override
                    public void run() {
                        try {
                            Bitmap bm = getBitmapFromUri(uri) ;
                            ImageView imageView = (ImageView) findViewById(R.id.imageView) ;
                            imageView.setImageBitmap  (bm);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
        }) ;  }};
        bm_thread.start();
    }

    public Bitmap getBitmapFromUri(Uri uri) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    }
}

Activity_Main.xml

<?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/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/ButtonL"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/ButtonL"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ButtonL"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/ButtonR"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ButtonR"
        app:layout_constraintBottom_toBottomOf="@+id/ButtonL"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/ButtonL"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:layout_weight="1.0"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

manifest

 

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.imageapplication">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GPS_ENABLE_REQUEST_CODE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.FLAG_GRANT_READ_URI_PERMISSION"/>
    <uses-permission android:name="android.permission.FLAG_GRANT_WRITE_URI_PERMISSION"/>
    <uses-permission android:name="android.permission.READ_USER_DICTIONARY"/>


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>
            <intent-filter>
                <action
                    android:name="android.intent.action.PICK"/>
                <category
                    android:name="android.intent.category.DEFAULT"/>
                <category
                    android:name="android.intent.category.OPENABLE"/>
                <data android:mimeType="text/plain"/>
                <data android:mimeType="image/*"/>
            </intent-filter>

            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.GET_CONTENT" />
                <!-- <data android:type="image/*" />  -->
                <category android:name="android.intent.category.DEFAULT" />
                <!-- The OPENABLE category declares that the returned file is accessible
                     from a content provider that supports OpenableColumns
                     and ContentResolver.openFileDescriptor() -->
                <category android:name="android.intent.category.OPENABLE" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND_MULTIPLE" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>

        </activity>
    </application>

</manifest>

 

기타1

webnautes.tistory.com

 

 

기타2

developer.android.com/reference/android/os/AsyncTask

 

 

기타3

developer.android.com/training/data-storage/files/external-scoped?hl=ko#java

 

 

기타4

g-y-e-o-m.tistory.com/107

 

 

////