2022年7月24日

Android Load Image from Url (Android 讀取網路圖片)

 




import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.media.ExifInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.view.Display;
import java.io.InputStream;

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {


public interface ActionListener {

public void get_image(Bitmap result_bmp);

}
public ActionListener actionListener=null;

private int max_width;
private int max_height;
private int img_roataion=0;
public DownloadImageTask(Activity activity){
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
max_width = size.x;
max_height = size.y;


}


private BitmapFactory.Options getBitmapOptions(int scale){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = scale;
options.inMutable=true;
return options;
}
private int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; }
return 0;
}
protected Bitmap doInBackground(String... urls) {

String urldisplay = urls[0];
Bitmap bitmap = null;
InputStream in;
BitmapFactory.Options options= getBitmapOptions(1);
options.inJustDecodeBounds=true;
try {



in = new java.net.URL(urldisplay).openStream();
if(Build.VERSION.SDK_INT>=24) {
ExifInterface exif = new ExifInterface(in);
int rotation1 = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
img_roataion = exifToDegrees(rotation1);
}
bitmap = BitmapFactory.decodeStream(in,null,options);

if(options.outWidth>max_width && options.outHeight>max_height){
options.inJustDecodeBounds=false;
options.inSampleSize=2;
in = new java.net.URL(urldisplay).openStream();
bitmap = BitmapFactory.decodeStream(in,null,options);

}else{
options.inJustDecodeBounds=false;
options.inSampleSize=1;
in = new java.net.URL(urldisplay).openStream();
bitmap = BitmapFactory.decodeStream(in,null,options);
}

if(img_roataion!=0 && bitmap!=null){
Matrix matrix = new Matrix();
matrix.postRotate(img_roataion);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
bitmap= rotatedBitmap;
}



} catch (Exception e) {
e.printStackTrace();
}




return bitmap;
}

protected void onPostExecute(Bitmap result) {

if(result==null)return;

if(actionListener!=null){
actionListener.get_image(result);
}

}
}


沒有留言:

張貼留言