본문 바로가기
카테고리 없음

[Android][Java] 사진 갤러리에 저장하기(최신)

by teamnova 2023. 9. 3.
728x90

https://stickode.tistory.com/324

 

[JAVA][Android] 사진 다운로드 하기

URI가 있을 때 사진을 다운로드 할 수 있는 코드입니다. 서버에서 가져온 이미지를 다운로드 버튼을 누를경우 나의 핸드폰 갤러리에 저장할 수 있습니다. 아래의 코드를 참고하세요. 스틱코드 게

stickode.tistory.com

URI가 있을 때 사진을 갤러리에 저장하는 코드를 업로드한 적 있는데,

기존코드가 동작하지 않는 경우가 있어서 다른 코드도 첨부합니다. 

 

 

* 시연화면

갤러리에 사진 저장하기 시연영상

* AndroidManifest.xml

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

 

* build.gradle

implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

 

* MainActivity.java

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView imageView = (ImageView)findViewById(R.id.imgFull);

        String imageUrl = "https://user-input-photo.s3.ap-northeast-2.amazonaws.com/front/10%EC%A7%84%EB%8F%97%EA%B0%9C_%EC%95%9E324.jpg"; // url을 입력해주세요
        Glide.with(getApplicationContext()).load(imageUrl).into(imageView);
        
        // 이미지를 갤러리에 저장
        downloadImageNew("dd", imageUrl); // 파일명, 저장할 사진 url

    }

    /*
        이 방법은 Android의 URL을 사용하여 인터넷에서 이미지를 다운로드하는 데 사용할 수 있습니다. 
        이 방법은 Android Download Manager를 사용하여 파일을 다운로드하여 갤러리에 추가합니다. 
        다운로드한 이미지가 ""에 저장됩니다
    */
    private void downloadImageNew(String filename, String downloadUrlOfImage){
        try{
            DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            Uri downloadUri = Uri.parse(downloadUrlOfImage);
            DownloadManager.Request request = new DownloadManager.Request(downloadUri);
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                    .setAllowedOverRoaming(false)
                    .setTitle(filename)
                    .setMimeType("image/jpeg") // Your file type. You can use this code to download other file types also.
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                    .setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,File.separator + filename + ".jpg");
            dm.enqueue(request);
            Toast.makeText(this, "Image download started.", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Toast.makeText(this, "Image download failed.", Toast.LENGTH_SHORT).show();
        }
    }

}

 

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 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:orientation="vertical"
tools:context=".MainActivity">

<ImageView
    android:id="@+id/imgFull"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="9.5" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="0.5"
    android:layout_gravity="right"
    >

    <Button
        android:id="@+id/btn_photoDown"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:text="다운로드" />

</LinearLayout>
</androidx.appcompat.widget.LinearLayoutCompat>