1000sj
SJ CODE
1000sj
전체 방문자
오늘
어제
  • 분류 전체보기
    • 알고리즘
    • 네트워크 보안
      • 네트워크
      • 보안
      • CTF
      • Exploit
    • System Programming
      • Operating System
      • Compiler
      • Device Driver
      • Emulator
    • Application Programming
      • Script
      • Android
    • 클라우드 컴퓨팅
      • Cloud Native
      • Public Cloud
      • Infrastructure
      • Database
      • DevOps
    • 트러블슈팅
    • ETC
      • 문화 생활
      • 커뮤니티

인기 글

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
1000sj

SJ CODE

[Android/Java] Sdcard에 이미지 다운로드
Application Programming/Android

[Android/Java] Sdcard에 이미지 다운로드

2021. 6. 14. 01:25

Demo

 

MainActivity.java

package com.example.recyclerview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView imageView;
    private Button btnDownload;

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

        imageView = findViewById(R.id.iv_show_image);
        btnDownload = findViewById(R.id.btn_download);
        btnDownload.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        new ImageDownloader().execute("https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdna%2FC4HHV%2Fbtq7ddyiCbT%2FAAAAAAAAAAAAAAAAAAAAAEGBZuEHQDkraZsKburPN9mYwm4gRoRlEj-h6Lr-l5X5%2Fimg.png%3Fcredential%3DyqXZFxpELC7KVnFOS48ylbz2pIh7yKj8%26expires%3D1751295599%26allow_ip%3D%26allow_referer%3D%26signature%3DPEBLKGQRay6ph42ZFIcnndWLgWI%253D");
    }

    private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
        private HttpURLConnection httpURLConnection;
        @Override
        protected Bitmap doInBackground(String... strings) {
            try {
                URL url = new URL(strings[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
                Bitmap temp = BitmapFactory.decodeStream(inputStream);
                return temp;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                httpURLConnection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if(bitmap != null) {
                imageView.setImageBitmap(bitmap);
                Toast.makeText(getApplicationContext(),"Download Success!!", Toast.LENGTH_SHORT).show();
                saveImage(bitmap);
            }else {
                Toast.makeText(getApplicationContext(),"Download Error!!", Toast.LENGTH_SHORT).show();
            }
        }

        private void saveImage(Bitmap bitmap) {
            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
            File myDirectory = new File(path + "/saved_images");
            if(!myDirectory.exists())
                myDirectory.mkdir();
            String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HHmmss").format(new Date());
            String imageName = timeStamp + ".jpg";
            myDirectory = new File(myDirectory, imageName);
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(myDirectory);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download Image" />

    <ImageView
        android:id="@+id/iv_show_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@drawable/sample" />
</LinearLayout>

/res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true"/>
</network-security-config>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.recyclerview">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    <application
        android:networkSecurityConfig="@xml/network_security_config"
        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/Theme.RecyclerView">
        <activity android:name=".MainActivity"

            android:theme="@style/Theme.AppCompat.NoActionBar"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity" android:parentActivityName=".MainActivity"/>
    </application>

</manifest>

'Application Programming > Android' 카테고리의 다른 글

[Android/Java] Text To Speech  (0) 2021.06.14
[Android/Java] 음성인식 해서 글로 변환  (0) 2021.06.14
[Android/Java] Image download using AsyncTask  (0) 2021.06.14
[Android/Java] bitmap 예제(00)  (0) 2021.06.13
[Android/Java] Media player(local storage)  (0) 2021.06.13
    'Application Programming/Android' 카테고리의 다른 글
    • [Android/Java] Text To Speech
    • [Android/Java] 음성인식 해서 글로 변환
    • [Android/Java] Image download using AsyncTask
    • [Android/Java] bitmap 예제(00)
    1000sj
    1000sj

    티스토리툴바