Libgdx实现异步加载网络图片并保存到SD卡或者data/data目录下边
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目录下边的更多相关文章
- android官方开源的高性能异步加载网络图片的Gridview例子
这个是我在安卓安卓巴士上看到的资料,放到这儿共享下.这个例子android官方提供的,其中讲解了如何异步加载网络图片,以及在gridview中高效率的显示图片此代码很好的解决了加载大量图片时,报OOM ...
- wemall app商城源码Android之ListView异步加载网络图片(优化缓存机制)
wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享wemall app商城源码Android之L ...
- Android相机、相册获取图片显示并保存到SD卡
Android相机.相册获取图片显示并保存到SD卡 [复制链接] 电梯直达 楼主 发表于 2013-3-13 19:51:43 | 只看该作者 |只看大图 本帖最后由 happy小妖同学 ...
- Android 将文件保存到SD卡,从卡中取文件,及删除文件
//保存到SD卡 private static String sdState = Environment.getExternalStorageState(); private static S ...
- [置顶] Android学习系列-把文件保存到SD卡上面(6)
Android学习系列-把文件保存到SD卡上面(5) 一般多媒体文件,大文件需要保存到SD卡中.关键点如下: 1,SD卡保存目录:mnt/sdcard,一般采用Environment.getExter ...
- Android开发调试日志工具类[支持保存到SD卡]
直接上代码: package com.example.callstatus; import java.io.File; import java.io.FileWriter; import java.i ...
- Android—将Bitmap图片保存到SD卡目录下或者指定目录
直接上代码就不废话啦 一:保存到SD卡下 File file = new File(Environment.getExternalStorageDirectory(), System.currentT ...
- Linux笔记(开机自动将kerne log保存到SD卡中)
有时候为了测试机器的稳定性,需要煲机测试几天的情况,这个时候机器已经封装好,不能再接串口线出来. 为了追溯问题,就需要将log信息保存下来. 于是就需要这样一个功能:系统启动后,自动将kernel的l ...
- UIImageView异步加载网络图片
在iOS开发过程中,经常会遇到使用UIImageView展现来自网络的图片的情况,最简单的做法如下: 去下载https://github.com/rs/SDWebImage放进你的工程里,加入头文件# ...
随机推荐
- OpenStack导入镜像后Launch不起来的几个问题
Dashboard上显示state为error 没有其他报错 用nova list找到虚拟机的id 然后nova show,可以得到fault详细信息 也可以查看下面两个log /var/log/no ...
- C#学习之在辅助线程中修改UI控件----invoke方法
Invoke and BeginInvoke 转载地址:http://www.cnblogs.com/worldreason/archive/2008/06/09/1216127.html 在Invo ...
- C#学习之------委托
1.向窗体中添加控件的最少步骤: 窗体的句柄为this private System.Windows.Forms.Button button1; ...
- shell 脚本阅读之二——ltp工具下的runltp
#!/bin/sh ################################################################################ ## ## ## ...
- mysql的基础操作
查看数据库 获取服务器上的数据库列表通常很有用.执行show databases;命令就可以搞定. mysql> show databases; 创建数据库 mysql> create d ...
- JavaScript下全选反选的Demo程序里实现checkmeonly函数 DOM
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Xcode的Hello World(简单易懂)
http://www.cocoachina.com/industry/20131121/7392.html http://objccn.io/issue-6-3/
- Introduction to the Build Lifecycle
Introduction to the Build Lifecycle Table Of Contents Build Lifecycle Basics Setting Up Your Project ...
- 如何查询一个库文件属于哪个rpm包
1.如果这个库文件已经存在 使用rpm命令: # rpm -qf /file/path (绝对路径) 例如: # rpm -qf /lib/libm.so.6 glibc-2.12-1.47.el ...
- 从汇编角度来理解linux下多层函数调用堆栈执行状态
注:在linux下开发经常使用的辅助小工具: readelf .hexdump.od.objdump.nm.telnet.nc 等,详细能够man一下. 我们用以下的C代码来研究函数调用的过程. C ...