Libgdx实现异步加载网络图片并保存到SD卡或者data/data目录下边,当本地有图片的时候,直接从本地读取图片,如果本地没有图片,将从服务器异步加载图片

package com.example.libgdx_net;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.PixmapIO;
import com.badlogic.gdx.graphics.Texture;
import android.content.Context;
import android.os.Environment;

public class ImageUtil {
private static final String SDCARD_CACHE_IMG_PATH = Environment
.getExternalStorageDirectory().getPath() + "/myGame/images/";
private static Texture texture;
private static Context mContext;
// 返回图片存到sd卡的路径
public static String getCacheImgPath() {
return SDCARD_CACHE_IMG_PATH;
}

public static String getDataImgPath() {
return mContext.getFilesDir().getPath();
}

public static String getImagePath(String url) {
if (isSDcardExist()) {
return getCacheImgPath().concat(ImageUtil.md5(url));
} else {
return getDataImgPath().concat(ImageUtil.md5(url));
}

}

/**
* 判断是否有存储卡,有返回TRUE,否则FALSE

* @return
*/
public static boolean isSDcardExist() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}

/**

* @return
* @throws IOException
*/
public static Texture loadImage(Context context,final String imgUrl,
final ImageCallBack imageCallback) {
mContext=context;
final String imagePath = getImagePath(imgUrl);
texture = getImageFromLocal(imagePath);
if (texture != null) {
return texture;
} else {// 从网上加载
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
URL url;
try {
url = new URL(imgUrl);
URLConnection conn = url.openConnection();
conn.connect();
final InputStream is = conn.getInputStream();
try {
saveImage(imagePath, is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Gdx.app.postRunnable(new Runnable() {  //这里是将texture 实例化到主线程

@Override
public void run() {
// TODO Auto-generated method stub
texture = getImageFromLocal(imagePath);
//Pixmap pixmap = texture.getTextureData().consumePixmap();
//savePixmap(imagePath,pixmap);
imageCallback.loadImage(texture, imagePath);
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
return null;
}
demo地址:

/**
* 从SD卡加载图片

* @param imagePath
* @return
*/
public static Texture getImageFromLocal(String imagePath) {
File file = new File(imagePath);
if (file.exists()) {
file.setLastModified(System.currentTimeMillis());
try {
final FileInputStream fis = new FileInputStream(imagePath);
Texture tures = new Texture(new FileHandle("image.jpg") {
@Override
public InputStream read() {
return fis;
}
});
return tures;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return null;
}
//public static void savePixmap(String imagePath,Pixmap pixmap){
//File f = new File(imagePath);
//if (f.exists()) {
//return;
//} else {
//File parentFile = f.getParentFile();
//if (!parentFile.exists()) {
//parentFile.mkdirs();
//}
//try {
//f.createNewFile();
//} catch (IOException e) {
//// TODO Auto-generated catch block
//e.printStackTrace();
//}
//FileHandle fh=new FileHandle(f);
//PixmapIO.writePNG(fh,pixmap);
//}
//
//}

/**
* 保存图片到SD卡

* @param imagePath
* @param buffer
* @throws IOException
*/
public static void saveImage(String imagePath, InputStream is)
throws IOException {
File f = new File(imagePath);
if (f.exists()) {
return;
} else {
File parentFile = f.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
f.createNewFile();
FileOutputStream fos = new FileOutputStream(imagePath);
try {
fos.write(readStream(is));
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**
* 将InputStream转换成byte数组

* @param b
* @return
*/
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 String md5(String paramString) {
String returnStr;
try {
MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
localMessageDigest.update(paramString.getBytes());
returnStr = byteToHexString(localMessageDigest.digest());
return returnStr;
} catch (Exception e) {
return paramString;
}
}

/**
* 将指定byte数组转换成16进制字符串

* @param b
* @return
*/
public static String byteToHexString(byte[] b) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
hexString.append(hex.toUpperCase());
}
return hexString.toString();
}

}

demo地址:http://download.csdn.net/detail/lihonghao1017/6249037

Libgdx实现异步加载网络图片并保存到SD卡或者data/data目录下边的更多相关文章

  1. android官方开源的高性能异步加载网络图片的Gridview例子

    这个是我在安卓安卓巴士上看到的资料,放到这儿共享下.这个例子android官方提供的,其中讲解了如何异步加载网络图片,以及在gridview中高效率的显示图片此代码很好的解决了加载大量图片时,报OOM ...

  2. wemall app商城源码Android之ListView异步加载网络图片(优化缓存机制)

    wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享wemall app商城源码Android之L ...

  3. Android相机、相册获取图片显示并保存到SD卡

    Android相机.相册获取图片显示并保存到SD卡 [复制链接]   电梯直达 楼主    发表于 2013-3-13 19:51:43 | 只看该作者 |只看大图  本帖最后由 happy小妖同学 ...

  4. Android 将文件保存到SD卡,从卡中取文件,及删除文件

    //保存到SD卡 private static String sdState = Environment.getExternalStorageState();     private static S ...

  5. [置顶] Android学习系列-把文件保存到SD卡上面(6)

    Android学习系列-把文件保存到SD卡上面(5) 一般多媒体文件,大文件需要保存到SD卡中.关键点如下: 1,SD卡保存目录:mnt/sdcard,一般采用Environment.getExter ...

  6. Android开发调试日志工具类[支持保存到SD卡]

    直接上代码: package com.example.callstatus; import java.io.File; import java.io.FileWriter; import java.i ...

  7. Android—将Bitmap图片保存到SD卡目录下或者指定目录

    直接上代码就不废话啦 一:保存到SD卡下 File file = new File(Environment.getExternalStorageDirectory(), System.currentT ...

  8. Linux笔记(开机自动将kerne log保存到SD卡中)

    有时候为了测试机器的稳定性,需要煲机测试几天的情况,这个时候机器已经封装好,不能再接串口线出来. 为了追溯问题,就需要将log信息保存下来. 于是就需要这样一个功能:系统启动后,自动将kernel的l ...

  9. UIImageView异步加载网络图片

    在iOS开发过程中,经常会遇到使用UIImageView展现来自网络的图片的情况,最简单的做法如下: 去下载https://github.com/rs/SDWebImage放进你的工程里,加入头文件# ...

随机推荐

  1. ceph install

    Ceph : performance, reliability and scalability storage solution Contents 1 Introduction 1.1 Testing ...

  2. 漂亮竖向菜单 有缓存 javascript

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. 设计模式 - 单例模式mysql数据库操作类

    待续... index.php 调用方法: <?php header('Content-Type:text/html; charset=utf8'); require 'instance.php ...

  4. poemel 端口作用

    clientPort 用于connetor组件启动时候,监听的调用,用于客户端连接 port用于服务器间通信,即rpc调用时候使用,在remote组件启动时候,生成remote,即gateway实例, ...

  5. C语言,链表反转

    倒序思路:依次把后面的节点移往头部. struct Node{ struct Node* next; int data; }; typedef struct Node NODE; NODE* inve ...

  6. arm汇编:ldr,str,ldm,stm,伪指令ldr

    ldr,str,ldm,stm的命名规律: 这几个指令命名看起来不易记住,现在找找规律. 指令 样本 效果 归纳名称解释 ldr Rd,addressing ldr r1,[r0] addressin ...

  7. 第三届蓝桥杯 c/c++真题

    第三届蓝桥杯真题 c/c++ 以下题目我自己也并不是所有的题目都是一次性就能做对或是有结题思路的.有些题目也是经过查证网上相关的资料或是参考了别人的代码和解题思路才做出来的.总的来看,这份题目考了很多 ...

  8. 利用ant的javac任务来编译java程序

    <?xml version="1.0" encoding="UTF-8"?> <project name="javaTest&quo ...

  9. NSStringDrawingOptions

    如果options参数为NSStringDrawingUsesLineFragmentOrigin,那么整个文本将以每行组成的矩形为单位计算整个文本的尺寸.(在这里有点奇怪,因为字体高度大概是13.8 ...

  10. Handler.removeMessages的作用,有时候为什么一定要先remove一下呢

    removeMessages会将handler对应message queue里的消息清空,如果带了int参数则是对应的消息清空.队列里面没有消息则handler会不工作,但不表示handler会停止. ...