Libgdx实现异步加载网络图片并保存到SD卡或者data/data目录下边

时间:2021-03-16 15:08:52

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