zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [java]转:String Date Calendar之间的转换
    ExtJs在页面上window再调用Window的事件处理
    java oracle clob string 大字符串存储【转】
    解决linux系统启动之:unexpected inconsistency:RUN fsck
    线程封闭之栈封闭和ThreadLocal
    Java线程状态和关闭线程的正确姿势
    指令重排序和内存屏障
    浅谈Java内存模型以及交互
    Redis分布式锁的一点小理解
    使用原生Ajax进行用户名重复的检验
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3315322.html
Copyright © 2011-2022 走看看