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. windows 下一个mysql password忘记改变

    到场mysql简介 my.ini 于[mysqld]以下被加入 skip-grant-tables win+R 热键 进cmd 然后输入命令net stop mysql  最后一点,使文件夹mysql ...

  2. 【OpenCV】OpenCV2.4.6 与Visiual Studio 2008,Python2.7.5配置和图像载入显示

    自从OpenCV2.2开始,OpenCV 库便分成几个模块并位于lib文件中,本节介绍从OpenCV2.4.6与VS2008 .Python2.7.5如何配置环境,如何外部文件载 入图像.在窗口中显示 ...

  3. MYSQLI - mysqli操作数据库

    <?php //模型类 class Model { //数据库连接 private $_conn = NULL; //where语句 private $_where = NULL; //表名称 ...

  4. 驱动:中断【2】中断处理程序、中断上下文中处理延时及一些函数的调用规则(调IIC中断驱动有感)

    中断处理程序.中断上下文中处理延时及一些函数的调用规则(调IIC中断驱动有感)http://blog.csdn.net/samantha_sun/article/details/6790492 1,中 ...

  5. 【centos6 , 7】 网络原理、网络配置

    第一部分:网络原理: 一.网络编址 (主要使用IP编址) 1.ip编址是一个双层编址方案,一个ip地址标识一个主机(或一个网卡接口) 2.现在应用最为广泛的是IPv4编址,已经开始逐渐向IPv6编址转 ...

  6. Python之路Day6

    Day6的主要内容是: configparser模块 shutil模块 subprocess模块 处理xml的模块 1.configparser模块 #! /usr/bin/env python # ...

  7. spider-web 是爬虫的网页版,使用xml配置

    spider-web 是爬虫的网页版,使用xml配置,支持大部分页面的爬取,支持爬取内容的保存.下载等. 其中配置文件格式为: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 ...

  8. grep命令參数及使用方法

    功能说明:查找文件中符合条件的字符串. 语 法:grep [-abcEFGhHilLnqrsvVwxy][-A<显示列数>][-B<显示列数>][-C<显示列数>] ...

  9. JVM调优总结(一)-- 一些概念

    数据类型 Java虚拟机中,数据类型可以分为两类:基本类型和引用类型.基本类型的变量保存原始值,即:他代表的值就是数值本身:而引用类型的变量保存引用值.“引用值”代表了某个对象的引用,而不是对象本身, ...

  10. 只启动一个zookeeper配置 server1只需要配置一个

    [root@wx03 conf]# cat zoo.cfg # The number of milliseconds of each tick tickTime=2000 # The number o ...