android开发实现下载网页图片到本地并显示

直接加载服务端返回的图片地址,耗时较多。做开屏广告时,展示不及时。

开发思路,第一次不加载广告,把服务端数据存在SharePreferences,但存的仅是地址。并没有实现下载,再次读取仍然需要联网。特此粘出代码。


在我们应用的类里SaveImageActivity.java

public class SaveImageActivity extends AppCompatActivity {
private ImageView showImg;
private Button btn;
private String fileName "openPicture";
private String pictureName "ad_id";
String filePath "ichong123.com/files/201";//可以随意百度一个图片地址

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_image);
showImg = (ImageView) findViewById(R.id.showImg);
btn = (Button) findViewById(R.id.btn);
ImgDonwloads.donwloadImg(thisfilePathfileNamepictureName);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ImgDonwloads.getImg(fileNamepictureName) != null) {
showImg.setImageBitmap(ImgDonwloads.getImg(fileNamepictureName));
showImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(SaveImageActivity.this"点击", Toast.LENGTH_LONG).show();
}
});
}
}
});

}


}



activity_save_image.xml

布局文件

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

<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击显示下载后的本地图片"
/>


<ImageView
android:id="@+id/showImg"
android:layout_marginTop="13dp"
android:layout_width="match_parent"
android:layout_height="150dp" 
/>

</LinearLayout>


工具类

ImgDonwloads.java


public class ImgDonwloads {

private static String urlPath;//网页路径
private static String filePath;//保存文件夹名
private static Bitmap mBitmap;
private static String mFileName;//保存文件名
private static String mSaveMessage;
private final static String TAG "ImgDonwloads";
private static Context context;
private static ProgressDialog mSaveDialog null;
static File appDir;



//下载图片
public static void donwloadImg(Context contexts, String url,String fileName ,String pictureName){
context = contexts;
urlPath = url;
filePath= fileName;
mFileName=pictureName;
mSaveDialog = ProgressDialog.show(context"保存图片""图片正在保存中,请稍等..."true);
new Thread(saveFileRunnable).start();//没有放线程会NetworkOnMainThreadException
}

private static Runnable saveFileRunnable new Runnable(){
@Override
public void run() {
try {
byte[] data = getImage(urlPath);
if(data!=null){
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
}else{
Toast.makeText(context"Image error!", Toast.LENGTH_LONG).show();
}
saveImage(mBitmap,filePath,mFileName);
mSaveMessage "Image success!";
catch (IOException e) {
mSaveMessage "Image error!";
e.printStackTrace();
catch (Exception e) {
e.printStackTrace();
}
messageHandler.sendMessage(messageHandler.obtainMessage());
}

};

private static Handler messageHandler new Handler() {
@Override
public void handleMessage(Message msg) {
mSaveDialog.dismiss();
Log.d(TAGmSaveMessage);
Toast.makeText(contextmSaveMessage, Toast.LENGTH_SHORT).show();
}
};





public static Bitmap getImg(String fileName , String pictureName){
appDir new File(Environment.getExternalStorageDirectory(), fileName);
if (!appDir.exists()) {
appDir.mkdir();
}
if(TextUtils.isEmpty(pictureName)){
pictureName=mFileName;
}
//读取本地图片
Bitmap bitmap = null;
try{
File avaterFile = new File(appDir, pictureName+".jpg");
if(avaterFile.exists()) {
bitmap = BitmapFactory.decodeFile(appDir+"/"+pictureName+".jpg");
}
catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}

/**
* Get image from newwork
@param path The path of image
@return byte[]
@throws Exception
*/
public static byte[] getImage(String path) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
return readStream(inStream);
}
return null;
}

/**
* Get data from stream
@param inStream
@return byte[]
@throws Exception
*/
public static byte[] readStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1){
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}

public static void saveImage(Bitmap bmp, String fileName,String name) {
appDir new File(Environment.getExternalStorageDirectory(), fileName);
if (!appDir.exists()) {
appDir.mkdir();
}
File file = new File(appDir, name+ ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
catch (FileNotFoundException e) {
e.printStackTrace();
catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
context
.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
}
}



在AndroidManifest.xml里面应该添加权限

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是实现从相册中选择照片并显示Android代码: 1. 在Manifest文件中添加读取外部存储权限: ```xml <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ``` 2. 在布局文件中添加一个ImageView用于显示选中的图片: ```xml <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:src="@drawable/ic_launcher_background" /> ``` 3. 在Activity或Fragment中添加以下代码实现从相册中选择照片并显示: ```java // 声明一个用于返回结果的常量 private static final int REQUEST_CODE_PICK_IMAGE = 1001; // 点击按钮选择照片 findViewById(R.id.buttonPickImage).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 创建Intent对象,设置类型为image/* Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType("image/*"); // 启动Intent,选择照片 startActivityForResult(Intent.createChooser(intent, "选择照片"), REQUEST_CODE_PICK_IMAGE); } }); // 处理选择照片的结果 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK && data != null) { // 获取选中的照片的URI Uri uri = data.getData(); // 将URI转换成Bitmap并显示在ImageView中 try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码中,我们首先声明了一个常量用于返回结果,然后在点击按钮时创建了一个Intent对象,设置类型为image/*,启动Intent,选择照片。最后在处理选择照片的结果时,获取选中的照片的URI,将URI转换成Bitmap并显示在ImageView中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值