Developer_hong

[안드로이드/Android] Layout 영역 사진첩 저장 + 미디어 스캔 본문

프로그래밍/안드로이드

[안드로이드/Android] Layout 영역 사진첩 저장 + 미디어 스캔

Developer_hong 2019. 11. 18. 17:38
반응형

기프티콘 저장과같이 선택한 영역 또는 view 부분만 캡쳐하여 사진첩에 저장하고 싶은 경우가 있다면

다음과같은 코드를  사용하면 된다.


/* Main_Activity.java */

public class MainActivity extends AppCompatActivity {

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

        LinearLayout capture_target_Layout = (LinearLayout)findViewById(R.id.capture_target_Layout); //캡쳐할 영역의 레이아웃
        Button capture_btn_Button = (Button)findViewById(R.id.capture_btn)


        SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmss"); //년,월,일,시간 포멧 설정
        Date time = new Date(); //파일명 중복 방지를 위해 사용될 현재시간
        String current_time = sdf.format(time); //String형 변수에 저장


        capture_btn_Button.setOnClickListener(new View.OnClickListener() { //캡쳐하기 클릭
            @Override
            public void onClick(View view) {
                Request_Capture(capture_target_Layout,current_time + "_capture"); //지정한 Layout 영역 사진첩 저장 요청
            }
        });
    }
}

/*Request_Capture.class 생성 */

public void Request_Capture(View view, String title){
   if(view==null){ //Null Point Exception ERROR 방지
   System.out.println("::::ERROR:::: view == NULL");
   return;
   }

  /* 캡쳐 파일 저장 */
  view.buildDrawingCache(); //캐시 비트 맵 만들기 
  Bitmap bitmap = view.getDrawingCache(); 
  FileOutputStream fos;

  /* 저장할 폴더 Setting */
  File uploadFolder = Environment.getExternalStoragePublicDirectory("/DCIM/Camera/"); //저장 경로 (File Type형 변수)



  if (!uploadFolder.exists()) { //만약 경로에 폴더가 없다면 
    uploadFolder.mkdir(); //폴더 생성
  }

  /* 파일 저장 */
  String Str_Path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/DCIM/Camera/"; //저장 경로 (String Type 변수)

  try{
     fos = new FileOutputStream(Str_Path+title+".jpg"); // 경로 + 제목 + .jpg로 FileOutputStream Setting
     bitmap.compress(Bitmap.CompressFormat.JPEG,80,fos);
  }catch (Exception e){
      e.printStackTrace();
  }

 //캡쳐 파일 미디어 스캔 (https://hongdroid.tistory.com/7)

 MediaScanner ms = MediaScanner.newInstance(getApplicationContext());



try { // TODO : 미디어 스캔
   ms.mediaScanning(Str_Path + title + ".jpg");
 }catch (Exception e) {
     e.printStackTrace();
     System.out.println("::::ERROR:::: "+e);
    }

}//End Function

/* 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"
    >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:id="@+id/capture_target_Layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:paddingTop="15dp"
                android:gravity="top|center"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:text="테스트 텍스트 ABC"
                />

            <ImageView
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="0dp"/>

            <TextView
                android:paddingBottom="15dp"
                android:gravity="bottom|center"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:text="테스트 텍스트 123"
                />

        </LinearLayout>

        <Button
            android:id="@+id/capture_btn"
            android:text="레이아웃 캡쳐"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

안드로이드 미디어 스캔 종류 : (https://hongdroid.tistory.com/6)

 

 

 

Manifest 에 외부 저장소 WRITE Permission 필요

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

* 안드로이드 6.0 (마시멜로) 이상이라면  https://gun0912.tistory.com/61 참고하여 적용 필요

 

반응형