Android异步加载网络图片

本文深入探讨了信息技术领域的核心组件及其应用,包括但不限于前端开发、后端开发、移动开发等细分领域。从基础概念到高级实践,为读者提供了一个全面而深入的理解视角。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android图片的异步加载,主要原理:

加载图片时先查看缓存中时候存在该图片,如果存在则返回该图片,否则先加载载一个默认的占位图片,同时创建一个通过网络获取图片的任务并添加,任务完成后放松消息给主线程更新界面。

使用方法:

  1. AsynImageLoader asynImageLoader = new AsynImageLoader();  
  2. asynImageLoader.showImageAsyn(imageView, imageUrl, resId);  
AsynImageLoader asynImageLoader = new AsynImageLoader();
asynImageLoader.showImageAsyn(imageView, imageUrl, resId);


 

 

类代码:

  1. package com.wangge.uumao.http;  
  2.   
  3. import java.lang.ref.SoftReference;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import android.graphics.Bitmap;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.util.Log;  
  13. import android.widget.ImageView;  
  14.   
  15. import com.wangge.uumao.util.PicUtil;  
  16.   
  17. public class AsynImageLoader {  
  18.     private static final String TAG = "AsynImageLoader";  
  19.     // 缓存下载过的图片的Map   
  20.     private Map<String, SoftReference<Bitmap>> caches;  
  21.     // 任务队列   
  22.     private List<Task> taskQueue;  
  23.     private boolean isRunning = false;  
  24.       
  25.     public AsynImageLoader(){  
  26.         // 初始化变量   
  27.         caches = new HashMap<String, SoftReference<Bitmap>>();  
  28.         taskQueue = new ArrayList<AsynImageLoader.Task>();  
  29.         // 启动图片下载线程   
  30.         isRunning = true;  
  31.         new Thread(runnable).start();  
  32.     }  
  33.       
  34.     /** 
  35.      *  
  36.      * @param imageView 需要延迟加载图片的对象 
  37.      * @param url 图片的URL地址 
  38.      * @param resId 图片加载过程中显示的图片资源 
  39.      */  
  40.     public void showImageAsyn(ImageView imageView, String url, int resId){  
  41.         imageView.setTag(url);  
  42.         Bitmap bitmap = loadImageAsyn(url, getImageCallback(imageView, resId));  
  43.           
  44.         if(bitmap == null){  
  45.             imageView.setImageResource(resId);  
  46.         }else{  
  47.             imageView.setImageBitmap(bitmap);  
  48.         }  
  49.     }  
  50.       
  51.     public Bitmap loadImageAsyn(String path, ImageCallback callback){  
  52.         // 判断缓存中是否已经存在该图片   
  53.         if(caches.containsKey(path)){  
  54.             // 取出软引用   
  55.             SoftReference<Bitmap> rf = caches.get(path);  
  56.             // 通过软引用,获取图片   
  57.             Bitmap bitmap = rf.get();  
  58.             // 如果该图片已经被释放,则将该path对应的键从Map中移除掉   
  59.             if(bitmap == null){  
  60.                 caches.remove(path);  
  61.             }else{  
  62.                 // 如果图片未被释放,直接返回该图片   
  63.                 Log.i(TAG, "return image in cache" + path);  
  64.                 return bitmap;  
  65.             }  
  66.         }else{  
  67.             // 如果缓存中不常在该图片,则创建图片下载任务   
  68.             Task task = new Task();  
  69.             task.path = path;  
  70.             task.callback = callback;  
  71.             Log.i(TAG, "new Task ," + path);  
  72.             if(!taskQueue.contains(task)){  
  73.                 taskQueue.add(task);  
  74.                 // 唤醒任务下载队列   
  75.                 synchronized (runnable) {  
  76.                     runnable.notify();  
  77.                 }  
  78.             }  
  79.         }  
  80.           
  81.         // 缓存中没有图片则返回null   
  82.         return null;  
  83.     }  
  84.       
  85.     /** 
  86.      *  
  87.      * @param imageView  
  88.      * @param resId 图片加载完成前显示的图片资源ID 
  89.      * @return 
  90.      */  
  91.     private ImageCallback getImageCallback(final ImageView imageView, final int resId){  
  92.         return new ImageCallback() {  
  93.               
  94.             @Override  
  95.             public void loadImage(String path, Bitmap bitmap) {  
  96.                 if(path.equals(imageView.getTag().toString())){  
  97.                     imageView.setImageBitmap(bitmap);  
  98.                 }else{  
  99.                     imageView.setImageResource(resId);  
  100.                 }  
  101.             }  
  102.         };  
  103.     }  
  104.       
  105.     private Handler handler = new Handler(){  
  106.   
  107.         @Override  
  108.         public void handleMessage(Message msg) {  
  109.             // 子线程中返回的下载完成的任务   
  110.             Task task = (Task)msg.obj;  
  111.             // 调用callback对象的loadImage方法,并将图片路径和图片回传给adapter   
  112.             task.callback.loadImage(task.path, task.bitmap);  
  113.         }  
  114.           
  115.     };  
  116.       
  117.     private Runnable runnable = new Runnable() {  
  118.           
  119.         @Override  
  120.         public void run() {  
  121.             while(isRunning){  
  122.                 // 当队列中还有未处理的任务时,执行下载任务   
  123.                 while(taskQueue.size() > 0){  
  124.                     // 获取第一个任务,并将之从任务队列中删除   
  125.                     Task task = taskQueue.remove(0);  
  126.                     // 将下载的图片添加到缓存   
  127.                     task.bitmap = PicUtil.getbitmap(task.path);  
  128.                     caches.put(task.path, new SoftReference<Bitmap>(task.bitmap));  
  129.                     if(handler != null){  
  130.                         // 创建消息对象,并将完成的任务添加到消息对象中   
  131.                         Message msg = handler.obtainMessage();  
  132.                         msg.obj = task;  
  133.                         // 发送消息回主线程   
  134.                         handler.sendMessage(msg);  
  135.                     }  
  136.                 }  
  137.                   
  138.                 //如果队列为空,则令线程等待   
  139.                 synchronized (this) {  
  140.                     try {  
  141.                         this.wait();  
  142.                     } catch (InterruptedException e) {  
  143.                         e.printStackTrace();  
  144.                     }  
  145.                 }  
  146.             }  
  147.         }  
  148.     };  
  149.       
  150.     //回调接口   
  151.     public interface ImageCallback{  
  152.         void loadImage(String path, Bitmap bitmap);  
  153.     }  
  154.       
  155.     class Task{  
  156.         // 下载任务的下载路径   
  157.         String path;  
  158.         // 下载的图片   
  159.         Bitmap bitmap;  
  160.         // 回调对象   
  161.         ImageCallback callback;  
  162.           
  163.         @Override  
  164.         public boolean equals(Object o) {  
  165.             Task task = (Task)o;  
  166.             return task.path.equals(path);  
  167.         }  
  168.     }  
  169. }  
package com.wangge.uumao.http;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.wangge.uumao.util.PicUtil;

public class AsynImageLoader {
	private static final String TAG = "AsynImageLoader";
	// 缓存下载过的图片的Map
	private Map<String, SoftReference<Bitmap>> caches;
	// 任务队列
	private List<Task> taskQueue;
	private boolean isRunning = false;
	
	public AsynImageLoader(){
		// 初始化变量
		caches = new HashMap<String, SoftReference<Bitmap>>();
		taskQueue = new ArrayList<AsynImageLoader.Task>();
		// 启动图片下载线程
		isRunning = true;
		new Thread(runnable).start();
	}
	
	/**
	 * 
	 * @param imageView 需要延迟加载图片的对象
	 * @param url 图片的URL地址
	 * @param resId 图片加载过程中显示的图片资源
	 */
	public void showImageAsyn(ImageView imageView, String url, int resId){
		imageView.setTag(url);
		Bitmap bitmap = loadImageAsyn(url, getImageCallback(imageView, resId));
		
		if(bitmap == null){
			imageView.setImageResource(resId);
		}else{
			imageView.setImageBitmap(bitmap);
		}
	}
	
	public Bitmap loadImageAsyn(String path, ImageCallback callback){
		// 判断缓存中是否已经存在该图片
		if(caches.containsKey(path)){
			// 取出软引用
			SoftReference<Bitmap> rf = caches.get(path);
			// 通过软引用,获取图片
			Bitmap bitmap = rf.get();
			// 如果该图片已经被释放,则将该path对应的键从Map中移除掉
			if(bitmap == null){
				caches.remove(path);
			}else{
				// 如果图片未被释放,直接返回该图片
				Log.i(TAG, "return image in cache" + path);
				return bitmap;
			}
		}else{
			// 如果缓存中不常在该图片,则创建图片下载任务
			Task task = new Task();
			task.path = path;
			task.callback = callback;
			Log.i(TAG, "new Task ," + path);
			if(!taskQueue.contains(task)){
				taskQueue.add(task);
				// 唤醒任务下载队列
				synchronized (runnable) {
					runnable.notify();
				}
			}
		}
		
		// 缓存中没有图片则返回null
		return null;
	}
	
	/**
	 * 
	 * @param imageView 
	 * @param resId 图片加载完成前显示的图片资源ID
	 * @return
	 */
	private ImageCallback getImageCallback(final ImageView imageView, final int resId){
		return new ImageCallback() {
			
			@Override
			public void loadImage(String path, Bitmap bitmap) {
				if(path.equals(imageView.getTag().toString())){
					imageView.setImageBitmap(bitmap);
				}else{
					imageView.setImageResource(resId);
				}
			}
		};
	}
	
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// 子线程中返回的下载完成的任务
			Task task = (Task)msg.obj;
			// 调用callback对象的loadImage方法,并将图片路径和图片回传给adapter
			task.callback.loadImage(task.path, task.bitmap);
		}
		
	};
	
	private Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			while(isRunning){
				// 当队列中还有未处理的任务时,执行下载任务
				while(taskQueue.size() > 0){
					// 获取第一个任务,并将之从任务队列中删除
					Task task = taskQueue.remove(0);
					// 将下载的图片添加到缓存
					task.bitmap = PicUtil.getbitmap(task.path);
					caches.put(task.path, new SoftReference<Bitmap>(task.bitmap));
					if(handler != null){
						// 创建消息对象,并将完成的任务添加到消息对象中
						Message msg = handler.obtainMessage();
						msg.obj = task;
						// 发送消息回主线程
						handler.sendMessage(msg);
					}
				}
				
				//如果队列为空,则令线程等待
				synchronized (this) {
					try {
						this.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	};
	
	//回调接口
	public interface ImageCallback{
		void loadImage(String path, Bitmap bitmap);
	}
	
	class Task{
		// 下载任务的下载路径
		String path;
		// 下载的图片
		Bitmap bitmap;
		// 回调对象
		ImageCallback callback;
		
		@Override
		public boolean equals(Object o) {
			Task task = (Task)o;
			return task.path.equals(path);
		}
	}
}


 最后附上PicUtil类的代码,之前忘了贴这个类的代码,不好意识了~~

  1. public class PicUtil {  
  2.     private static final String TAG = "PicUtil";  
  3.   
  4.     /** 
  5.      * 根据一个网络连接(URL)获取bitmapDrawable图像 
  6.      *  
  7.      * @param imageUri 
  8.      * @return 
  9.      */  
  10.     public static BitmapDrawable getfriendicon(URL imageUri) {  
  11.   
  12.         BitmapDrawable icon = null;  
  13.         try {  
  14.             HttpURLConnection hp = (HttpURLConnection) imageUri  
  15.                     .openConnection();  
  16.             icon = new BitmapDrawable(hp.getInputStream());// 将输入流转换成bitmap   
  17.             hp.disconnect();// 关闭连接   
  18.         } catch (Exception e) {  
  19.         }  
  20.         return icon;  
  21.     }  
  22.   
  23.     /** 
  24.      * 根据一个网络连接(String)获取bitmapDrawable图像 
  25.      *  
  26.      * @param imageUri 
  27.      * @return 
  28.      */  
  29.     public static BitmapDrawable getcontentPic(String imageUri) {  
  30.         URL imgUrl = null;  
  31.         try {  
  32.             imgUrl = new URL(imageUri);  
  33.         } catch (MalformedURLException e1) {  
  34.             e1.printStackTrace();  
  35.         }  
  36.         BitmapDrawable icon = null;  
  37.         try {  
  38.             HttpURLConnection hp = (HttpURLConnection) imgUrl.openConnection();  
  39.             icon = new BitmapDrawable(hp.getInputStream());// 将输入流转换成bitmap   
  40.             hp.disconnect();// 关闭连接   
  41.         } catch (Exception e) {  
  42.         }  
  43.         return icon;  
  44.     }  
  45.   
  46.     /** 
  47.      * 根据一个网络连接(URL)获取bitmap图像 
  48.      *  
  49.      * @param imageUri 
  50.      * @return 
  51.      */  
  52.     public static Bitmap getusericon(URL imageUri) {  
  53.         // 显示网络上的图片   
  54.         URL myFileUrl = imageUri;  
  55.         Bitmap bitmap = null;  
  56.         try {  
  57.             HttpURLConnection conn = (HttpURLConnection) myFileUrl  
  58.                     .openConnection();  
  59.             conn.setDoInput(true);  
  60.             conn.connect();  
  61.             InputStream is = conn.getInputStream();  
  62.             bitmap = BitmapFactory.decodeStream(is);  
  63.             is.close();  
  64.         } catch (IOException e) {  
  65.             e.printStackTrace();  
  66.         }  
  67.         return bitmap;  
  68.     }  
  69.   
  70.     /** 
  71.      * 根据一个网络连接(String)获取bitmap图像 
  72.      *  
  73.      * @param imageUri 
  74.      * @return 
  75.      * @throws MalformedURLException 
  76.      */  
  77.     public static Bitmap getbitmap(String imageUri) {  
  78.         // 显示网络上的图片   
  79.         Bitmap bitmap = null;  
  80.         try {  
  81.             URL myFileUrl = new URL(imageUri);  
  82.             HttpURLConnection conn = (HttpURLConnection) myFileUrl  
  83.                     .openConnection();  
  84.             conn.setDoInput(true);  
  85.             conn.connect();  
  86.             InputStream is = conn.getInputStream();  
  87.             bitmap = BitmapFactory.decodeStream(is);  
  88.             is.close();  
  89.   
  90.             Log.i(TAG, "image download finished." + imageUri);  
  91.         } catch (IOException e) {  
  92.             e.printStackTrace();  
  93.             return null;  
  94.         }  
  95.         return bitmap;  
  96.     }  
  97.   
  98.     /** 
  99.      * 下载图片 同时写道本地缓存文件中 
  100.      *  
  101.      * @param context 
  102.      * @param imageUri 
  103.      * @return 
  104.      * @throws MalformedURLException 
  105.      */  
  106.     public static Bitmap getbitmapAndwrite(String imageUri) {  
  107.         Bitmap bitmap = null;  
  108.         try {  
  109.             // 显示网络上的图片   
  110.             URL myFileUrl = new URL(imageUri);  
  111.             HttpURLConnection conn = (HttpURLConnection) myFileUrl  
  112.                     .openConnection();  
  113.             conn.setDoInput(true);  
  114.             conn.connect();  
  115.   
  116.             InputStream is = conn.getInputStream();  
  117.             File cacheFile = FileUtil.getCacheFile(imageUri);  
  118.             BufferedOutputStream bos = null;  
  119.             bos = new BufferedOutputStream(new FileOutputStream(cacheFile));  
  120.             Log.i(TAG, "write file to " + cacheFile.getCanonicalPath());  
  121.   
  122.             byte[] buf = new byte[1024];  
  123.             int len = 0;  
  124.             // 将网络上的图片存储到本地   
  125.             while ((len = is.read(buf)) > 0) {  
  126.                 bos.write(buf, 0, len);  
  127.             }  
  128.   
  129.             is.close();  
  130.             bos.close();  
  131.   
  132.             // 从本地加载图片   
  133.             bitmap = BitmapFactory.decodeFile(cacheFile.getCanonicalPath());  
  134.             String name = MD5Util.MD5(imageUri);  
  135.   
  136.         } catch (IOException e) {  
  137.             e.printStackTrace();  
  138.         }  
  139.         return bitmap;  
  140.     }  
  141.   
  142.     public static boolean downpic(String picName, Bitmap bitmap) {  
  143.         boolean nowbol = false;  
  144.         try {  
  145.             File saveFile = new File("/mnt/sdcard/download/weibopic/" + picName  
  146.                     + ".png");  
  147.             if (!saveFile.exists()) {  
  148.                 saveFile.createNewFile();  
  149.             }  
  150.             FileOutputStream saveFileOutputStream;  
  151.             saveFileOutputStream = new FileOutputStream(saveFile);  
  152.             nowbol = bitmap.compress(Bitmap.CompressFormat.PNG, 100,  
  153.                     saveFileOutputStream);  
  154.             saveFileOutputStream.close();  
  155.         } catch (FileNotFoundException e) {  
  156.             e.printStackTrace();  
  157.         } catch (IOException e) {  
  158.             e.printStackTrace();  
  159.         } catch (Exception e) {  
  160.             e.printStackTrace();  
  161.         }  
  162.         return nowbol;  
  163.     }  
  164.   
  165.     public static void writeTofiles(Context context, Bitmap bitmap,  
  166.             String filename) {  
  167.         BufferedOutputStream outputStream = null;  
  168.         try {  
  169.             outputStream = new BufferedOutputStream(context.openFileOutput(  
  170.                     filename, Context.MODE_PRIVATE));  
  171.             bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);  
  172.         } catch (FileNotFoundException e) {  
  173.             e.printStackTrace();  
  174.         }  
  175.     }  
  176.   
  177.     /** 
  178.      * 将文件写入缓存系统中 
  179.      *  
  180.      * @param filename 
  181.      * @param is 
  182.      * @return 
  183.      */  
  184.     public static String writefile(Context context, String filename,  
  185.             InputStream is) {  
  186.         BufferedInputStream inputStream = null;  
  187.         BufferedOutputStream outputStream = null;  
  188.         try {  
  189.             inputStream = new BufferedInputStream(is);  
  190.             outputStream = new BufferedOutputStream(context.openFileOutput(  
  191.                     filename, Context.MODE_PRIVATE));  
  192.             byte[] buffer = new byte[1024];  
  193.             int length;  
  194.             while ((length = inputStream.read(buffer)) != -1) {  
  195.                 outputStream.write(buffer, 0, length);  
  196.             }  
  197.         } catch (Exception e) {  
  198.         } finally {  
  199.             if (inputStream != null) {  
  200.                 try {  
  201.                     inputStream.close();  
  202.                 } catch (IOException e) {  
  203.                     e.printStackTrace();  
  204.                 }  
  205.             }  
  206.             if (outputStream != null) {  
  207.                 try {  
  208.                     outputStream.flush();  
  209.                     outputStream.close();  
  210.                 } catch (IOException e) {  
  211.                     e.printStackTrace();  
  212.                 }  
  213.             }  
  214.         }  
  215.         return context.getFilesDir() + "/" + filename + ".jpg";  
  216.     }  
  217.   
  218.     // 放大缩小图片   
  219.     public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {  
  220.         int width = bitmap.getWidth();  
  221.         int height = bitmap.getHeight();  
  222.         Matrix matrix = new Matrix();  
  223.         float scaleWidht = ((float) w / width);  
  224.         float scaleHeight = ((float) h / height);  
  225.         matrix.postScale(scaleWidht, scaleHeight);  
  226.         Bitmap newbmp = Bitmap.createBitmap(bitmap, 00, width, height,  
  227.                 matrix, true);  
  228.         return newbmp;  
  229.     }  
  230.   
  231.     // 将Drawable转化为Bitmap   
  232.     public static Bitmap drawableToBitmap(Drawable drawable) {  
  233.         int width = drawable.getIntrinsicWidth();  
  234.         int height = drawable.getIntrinsicHeight();  
  235.         Bitmap bitmap = Bitmap.createBitmap(width, height, drawable  
  236.                 .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  
  237.                 : Bitmap.Config.RGB_565);  
  238.         Canvas canvas = new Canvas(bitmap);  
  239.         drawable.setBounds(00, width, height);  
  240.         drawable.draw(canvas);  
  241.         return bitmap;  
  242.   
  243.     }  
  244.   
  245.     // 获得圆角图片的方法   
  246.     public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {  
  247.         if(bitmap == null){  
  248.             return null;  
  249.         }  
  250.           
  251.         Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),  
  252.                 bitmap.getHeight(), Config.ARGB_8888);  
  253.         Canvas canvas = new Canvas(output);  
  254.   
  255.         final int color = 0xff424242;  
  256.         final Paint paint = new Paint();  
  257.         final Rect rect = new Rect(00, bitmap.getWidth(), bitmap.getHeight());  
  258.         final RectF rectF = new RectF(rect);  
  259.   
  260.         paint.setAntiAlias(true);  
  261.         canvas.drawARGB(0000);  
  262.         paint.setColor(color);  
  263.         canvas.drawRoundRect(rectF, roundPx, roundPx, paint);  
  264.   
  265.         paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));  
  266.         canvas.drawBitmap(bitmap, rect, rect, paint);  
  267.         return output;  
  268.     }  
  269.   
  270.     // 获得带倒影的图片方法   
  271.     public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {  
  272.         final int reflectionGap = 4;  
  273.         int width = bitmap.getWidth();  
  274.         int height = bitmap.getHeight();  
  275.   
  276.         Matrix matrix = new Matrix();  
  277.         matrix.preScale(1, -1);  
  278.   
  279.         Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,  
  280.                 width, height / 2, matrix, false);  
  281.   
  282.         Bitmap bitmapWithReflection = Bitmap.createBitmap(width,  
  283.                 (height + height / 2), Config.ARGB_8888);  
  284.   
  285.         Canvas canvas = new Canvas(bitmapWithReflection);  
  286.         canvas.drawBitmap(bitmap, 00null);  
  287.         Paint deafalutPaint = new Paint();  
  288.         canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);  
  289.   
  290.         canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);  
  291.   
  292.         Paint paint = new Paint();  
  293.         LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,  
  294.                 bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,  
  295.                 0x00ffffff, TileMode.CLAMP);  
  296.         paint.setShader(shader);  
  297.         // Set the Transfer mode to be porter duff and destination in   
  298.         paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));  
  299.         // Draw a rectangle using the paint with our linear gradient   
  300.         canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()  
  301.                 + reflectionGap, paint);  
  302.   
  303.         return bitmapWithReflection;  
  304.     }  
  305.   
  306. }  
public class PicUtil {
	private static final String TAG = "PicUtil";

	/**
	 * 根据一个网络连接(URL)获取bitmapDrawable图像
	 * 
	 * @param imageUri
	 * @return
	 */
	public static BitmapDrawable getfriendicon(URL imageUri) {

		BitmapDrawable icon = null;
		try {
			HttpURLConnection hp = (HttpURLConnection) imageUri
					.openConnection();
			icon = new BitmapDrawable(hp.getInputStream());// 将输入流转换成bitmap
			hp.disconnect();// 关闭连接
		} catch (Exception e) {
		}
		return icon;
	}

	/**
	 * 根据一个网络连接(String)获取bitmapDrawable图像
	 * 
	 * @param imageUri
	 * @return
	 */
	public static BitmapDrawable getcontentPic(String imageUri) {
		URL imgUrl = null;
		try {
			imgUrl = new URL(imageUri);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		BitmapDrawable icon = null;
		try {
			HttpURLConnection hp = (HttpURLConnection) imgUrl.openConnection();
			icon = new BitmapDrawable(hp.getInputStream());// 将输入流转换成bitmap
			hp.disconnect();// 关闭连接
		} catch (Exception e) {
		}
		return icon;
	}

	/**
	 * 根据一个网络连接(URL)获取bitmap图像
	 * 
	 * @param imageUri
	 * @return
	 */
	public static Bitmap getusericon(URL imageUri) {
		// 显示网络上的图片
		URL myFileUrl = imageUri;
		Bitmap bitmap = null;
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	/**
	 * 根据一个网络连接(String)获取bitmap图像
	 * 
	 * @param imageUri
	 * @return
	 * @throws MalformedURLException
	 */
	public static Bitmap getbitmap(String imageUri) {
		// 显示网络上的图片
		Bitmap bitmap = null;
		try {
			URL myFileUrl = new URL(imageUri);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();

			Log.i(TAG, "image download finished." + imageUri);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	/**
	 * 下载图片 同时写道本地缓存文件中
	 * 
	 * @param context
	 * @param imageUri
	 * @return
	 * @throws MalformedURLException
	 */
	public static Bitmap getbitmapAndwrite(String imageUri) {
		Bitmap bitmap = null;
		try {
			// 显示网络上的图片
			URL myFileUrl = new URL(imageUri);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();

			InputStream is = conn.getInputStream();
			File cacheFile = FileUtil.getCacheFile(imageUri);
			BufferedOutputStream bos = null;
			bos = new BufferedOutputStream(new FileOutputStream(cacheFile));
			Log.i(TAG, "write file to " + cacheFile.getCanonicalPath());

			byte[] buf = new byte[1024];
			int len = 0;
			// 将网络上的图片存储到本地
			while ((len = is.read(buf)) > 0) {
				bos.write(buf, 0, len);
			}

			is.close();
			bos.close();

			// 从本地加载图片
			bitmap = BitmapFactory.decodeFile(cacheFile.getCanonicalPath());
			String name = MD5Util.MD5(imageUri);

		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	public static boolean downpic(String picName, Bitmap bitmap) {
		boolean nowbol = false;
		try {
			File saveFile = new File("/mnt/sdcard/download/weibopic/" + picName
					+ ".png");
			if (!saveFile.exists()) {
				saveFile.createNewFile();
			}
			FileOutputStream saveFileOutputStream;
			saveFileOutputStream = new FileOutputStream(saveFile);
			nowbol = bitmap.compress(Bitmap.CompressFormat.PNG, 100,
					saveFileOutputStream);
			saveFileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nowbol;
	}

	public static void writeTofiles(Context context, Bitmap bitmap,
			String filename) {
		BufferedOutputStream outputStream = null;
		try {
			outputStream = new BufferedOutputStream(context.openFileOutput(
					filename, Context.MODE_PRIVATE));
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将文件写入缓存系统中
	 * 
	 * @param filename
	 * @param is
	 * @return
	 */
	public static String writefile(Context context, String filename,
			InputStream is) {
		BufferedInputStream inputStream = null;
		BufferedOutputStream outputStream = null;
		try {
			inputStream = new BufferedInputStream(is);
			outputStream = new BufferedOutputStream(context.openFileOutput(
					filename, Context.MODE_PRIVATE));
			byte[] buffer = new byte[1024];
			int length;
			while ((length = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, length);
			}
		} catch (Exception e) {
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.flush();
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return context.getFilesDir() + "/" + filename + ".jpg";
	}

	// 放大缩小图片
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidht = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidht, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;
	}

	// 将Drawable转化为Bitmap
	public static Bitmap drawableToBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();
		Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
				.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);
		drawable.draw(canvas);
		return bitmap;

	}

	// 获得圆角图片的方法
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
		if(bitmap == null){
			return null;
		}
		
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	// 获得带倒影的图片方法
	public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
		final int reflectionGap = 4;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
				width, height / 2, matrix, false);

		Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
				(height + height / 2), Config.ARGB_8888);

		Canvas canvas = new Canvas(bitmapWithReflection);
		canvas.drawBitmap(bitmap, 0, 0, null);
		Paint deafalutPaint = new Paint();
		canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);

		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
				bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
				0x00ffffff, TileMode.CLAMP);
		paint.setShader(shader);
		// Set the Transfer mode to be porter duff and destination in
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		// Draw a rectangle using the paint with our linear gradient
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
				+ reflectionGap, paint);

		return bitmapWithReflection;
	}

}


 FileUtil

  1. package com.wangge.coupon.util;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import android.os.Environment;  
  7. import android.util.Log;  
  8.   
  9. import com.wangge.coupon.http.AsynImageLoader;  
  10.   
  11. public class FileUtil {  
  12.     private static final String TAG = "FileUtil";  
  13.   
  14.     public static File getCacheFile(String imageUri){  
  15.         File cacheFile = null;  
  16.         try {  
  17.             if (Environment.getExternalStorageState().equals(  
  18.                     Environment.MEDIA_MOUNTED)) {  
  19.                 File sdCardDir = Environment.getExternalStorageDirectory();  
  20.                 String fileName = getFileName(imageUri);  
  21.                 File dir = new File(sdCardDir.getCanonicalPath()  
  22.                         + AsynImageLoader.CACHE_DIR);  
  23.                 if (!dir.exists()) {  
  24.                     dir.mkdirs();  
  25.                 }  
  26.                 cacheFile = new File(dir, fileName);  
  27.                 Log.i(TAG, "exists:" + cacheFile.exists() + ",dir:" + dir + ",file:" + fileName);  
  28.             }    
  29.         } catch (IOException e) {  
  30.             e.printStackTrace();  
  31.             Log.e(TAG, "getCacheFileError:" + e.getMessage());  
  32.         }  
  33.           
  34.         return cacheFile;  
  35.     }  
  36.       
  37.     public static String getFileName(String path) {  
  38.         int index = path.lastIndexOf("/");  
  39.         return path.substring(index + 1);  
  40.     }  
  41. }  
package com.wangge.coupon.util;

import java.io.File;
import java.io.IOException;

import android.os.Environment;
import android.util.Log;

import com.wangge.coupon.http.AsynImageLoader;

public class FileUtil {
	private static final String TAG = "FileUtil";

	public static File getCacheFile(String imageUri){
		File cacheFile = null;
		try {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File sdCardDir = Environment.getExternalStorageDirectory();
				String fileName = getFileName(imageUri);
				File dir = new File(sdCardDir.getCanonicalPath()
						+ AsynImageLoader.CACHE_DIR);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				cacheFile = new File(dir, fileName);
				Log.i(TAG, "exists:" + cacheFile.exists() + ",dir:" + dir + ",file:" + fileName);
			}  
		} catch (IOException e) {
			e.printStackTrace();
			Log.e(TAG, "getCacheFileError:" + e.getMessage());
		}
		
		return cacheFile;
	}
	
	public static String getFileName(String path) {
		int index = path.lastIndexOf("/");
		return path.substring(index + 1);
	}
}


内容概要:本文详细探讨了基于阻尼连续可调减振器(CDC)的半主动悬架系统的控制策略。首先建立了CDC减振器的动力学模型,验证了其阻尼特性,并通过实验确认了模型的准确性。接着,搭建了1/4车辆悬架模型,分析了不同阻尼系数对悬架性能的影响。随后,引入了PID、自适应模糊PID和模糊-PID并联三种控制策略,通过仿真比较它们的性能提升效果。研究表明,模糊-PID并联控制能最优地提升悬架综合性能,在平顺性和稳定性间取得最佳平衡。此外,还深入分析了CDC减振器的特性,优化了控制策略,并进行了系统级验证。 适用人群:从事汽车工程、机械工程及相关领域的研究人员和技术人员,尤其是对车辆悬架系统和控制策略感兴趣的读者。 使用场景及目标:①适用于研究和开发基于CDC减振器的半主动悬架系统的工程师;②帮助理解不同控制策略(如PID、模糊PID、模糊-PID并联)在悬架系统中的应用及其性能差异;③为优化车辆行驶舒适性和稳定性提供理论依据和技术支持。 其他说明:本文不仅提供了详细的数学模型和仿真代码,还通过实验数据验证了模型的准确性。对于希望深入了解CDC减振器工作原理及其控制策略的读者来说,本文是一份极具价值的参考资料。同时,文中还介绍了多种控制策略的具体实现方法及其优缺点,为后续的研究和实际应用提供了有益的借鉴。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值