Android微信分享图片大于32k进行压缩

微信分享视频的时候,需要传一个图片数组,大小不能大于32k。  

解决方案:使用Bitmap自带的compress方法解决了这个问题.


源码如下:

<span style="font-size:14px;">package com.example.test;

import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		new LoadPicThread("http://7xjp2s.dl2.z0.glb.qiniucdn.com/2015/07/01/2248c3025a9989f062ce8b8c52a72481_m.jpg",new Handler(){
			@Override
			public void handleMessage(Message msg) {
				byte[] bytes=(byte[]) msg.obj;
				if(bytes.length>IMAGE_SIZE){
					Toast.makeText(MainActivity.this, "图片尺寸太大", 0).show();
					return;
				}
				System.out.println("视频截屏图片长度:"+bytes.length);
			}
		}).start();
	}
	
	
	public static final int IMAGE_SIZE=32768;//微信分享图片大小限制
	private class LoadPicThread extends Thread{
		private String url;
		private Handler handler;
		public LoadPicThread(String url,Handler handler){
			this.url=url;
			this.handler=handler;
		}
		
		@Override
		public void run(){
			try {
				URL picurl = new URL(url); 
				HttpURLConnection conn = (HttpURLConnection)picurl.openConnection(); // 获得连接 
				conn.setConnectTimeout(6000);//设置超时 
				conn.setDoInput(true); 
				conn.setUseCaches(false);//不缓存 
				conn.connect();
				Bitmap bmp=BitmapFactory.decodeStream(conn.getInputStream());
				
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				
				bmp.compress(Bitmap.CompressFormat.JPEG, 100, output);
				int options = 100;
				while (output.toByteArray().length > IMAGE_SIZE && options != 10) { 
					output.reset(); //清空baos
					bmp.compress(Bitmap.CompressFormat.JPEG, options, output);//这里压缩options%,把压缩后的数据存放到baos中  
		            options -= 10;
				}
				
				bmp.recycle();
				byte[] result = output.toByteArray();
				output.close();
				
				Message message=handler.obtainMessage();
				message.obj=result;
				message.sendToTarget();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}</span><span style="font-size: 18px;">
</span>


主要开启一个线程读取服务器图片.用while循环压缩图片。。。图片小于32k或者已经压缩了9次退出循环

你可能感兴趣的:(图片压缩,微信分享视频)