我们从网上获取图片有时太大我们的手机分辨率不够所以我们就得把图片压缩
下面就是从网上获取图片直接压缩的代码
package com.example.tupian;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.R.integer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
public class MainActivity extends Activity {
String path="http://guaju.github.io/flower2.jpg";
private HttpURLConnection conn;
private ImageView iv;
private ProgressDialog progressDialog;
private BufferedInputStream bufferedInputStream;
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
compressImage();
}
private void compressImage() {
//异步加载框架
new MyAsync() {
@Override//加载前
public void perLoad() {
//进度条对话框
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.show();//显示对话框
}
@Override//加载中
public void loading() {
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code==200){//判断是否联网成功
//得到流
InputStream inputStream = conn.getInputStream();
// bufferedInputStream = new BufferedInputStream(inputStream);
// bufferedInputStream.mark(bufferedInputStream.available());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int temp=0;
byte[] b=new byte[1024];
while((temp=inputStream.read(b))!=-1){
baos.write(b, 0, temp);
}
baos.close();
inputStream.close();
byte[] array = baos.toByteArray();
/*压缩图片
* 一:先拿到图片的分辨率
* 1:得到Option
* 2:设置Option的一个取值方式
* 3:把Option与图片关联
* 4:取出图片大小
* 二:计算压缩比例(一般用480*800或者获取屏幕分辨率然后计算)
* 1:设置比例(如果实际照片宽大,那么就计算成宽的比例,反之亦然)
* 2:设置Option的压缩比例并且设置压缩方式
* 3:关联BitmapFactory去压缩图片
*/
Options options = new BitmapFactory.Options();//得到Option
options.inJustDecodeBounds=true;//只是解析一下图片大小,不看内容,节省了空间和内存
// BitmapFactory.decodeStream(bufferedInputStream, null, options);
//关联图片
BitmapFactory.decodeByteArray(array, 0, array.length,options);
//得到图片的宽和高
int outHeight=options.outHeight;
int outWidth=options.outWidth;
System.out.println("hhhhh"+outHeight+"wwww"+outWidth);
// int hh=480f;
// int ww=800f;
//获取屏幕分辨率
WindowManager manager = getWindowManager();
Display display = manager.getDefaultDisplay();//拿到持有屏幕参数的类
DisplayMetrics metrics = new DisplayMetrics();//屏幕的值
display.getMetrics(metrics);
int hh=metrics.heightPixels;
int ww=metrics.widthPixels;
int i=1;//压缩比例 1表示不作压缩
if(outWidth>outHeight&&outWidth>ww){
i=outWidth/ww;
}else if (outHeight>outWidth&&outHeight>hh) {
i=outHeight/hh;
}else {
i=1;
}
options.inSampleSize=i;//按照什么比例压缩
options.inJustDecodeBounds=false;//设置option的测量方式改成能读取图片
// bufferedInputStream.reset();
// bitmap = BitmapFactory.decodeStream(bufferedInputStream, null, options);
//关联图片
bitmap=BitmapFactory.decodeByteArray(array, 0, array.length, options);
// inputStream.close();
// bufferedInputStream.close();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "加载成功", 0).show();
}
});
}
else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "加载失败", 0).show();
}
});
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override//加载后
public void afterLoad() {
progressDialog.dismiss();//隐藏对话框
iv.setImageBitmap(bitmap);//显示压缩过的图片
}
}.exe();
}
private void initView() {
iv = (ImageView) findViewById(R.id.iv);
}
}
异步加载框架
<pre name="code" class="java">package com.example.tupian;
import android.os.Handler;
public abstract class MyAsync {
public abstract void perLoad();
public abstract void loading();
public abstract void afterLoad();
public Handler myhHandler=new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what==1){
afterLoad();
}
};
};
public void exe(){
perLoad();
new Thread(new Runnable() {
@Override
public void run() {
loading();
myhHandler.sendEmptyMessage(1);
}
}).start();
}
}
</pre><pre name="code" class="java">布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
先存到本地后压缩
<pre name="code" class="java">package com.example.piccompress;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
public class MainActivity extends Activity {
String path="http://b.hiphotos.baidu.com/zhidao/pic/item/a686c9177f3e6709b0f3328939c79f3df9dc55d0.jpg";
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
System.out.println("hkjjhkhnlhk");
//加载图片
String data = initData();
System.out.println(data);
//压缩图片z
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeFile(data, options);
int outWidth = options.outWidth;
int outHeight = options.outHeight;
System.out.println("宽"+outWidth+"高"+outHeight);
//计算压缩比例
int scale=1;//压缩比列 1表示不做压缩
float actWidth=480;
float actHeight=800;
// WindowManager manager = getWindowManager();
// Display display = manager.getDefaultDisplay();
// int width = display.getWidth();
// int height = display.getHeight();
// float actHeight=display.getHeight();
// float actWidth=display.getWidth();
//
if(outWidth>outHeight&&outWidth>actWidth){
scale=(int) (outWidth/actWidth);
}else if (outHeight>outWidth&&outHeight>actHeight) {
scale=(int) (outHeight/actHeight);
}else {
scale=1;
}
options.inSampleSize=scale;
options.inJustDecodeBounds=false;
Bitmap bitmap = BitmapFactory.decodeFile(data, options);
iv.setImageBitmap(bitmap);
}
private String initData() {
new MyAsync() {
private ProgressDialog pd;
private HttpURLConnection conn;
@Override
public void preLoad() {
//进度条对话框
pd = new ProgressDialog(MainActivity.this);
pd.show();
}
@Override
public void loading() {
try {
URL url = new URL(path);
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code==200){
try {
System.out.println("jkshfskhfalk");
InputStream is = conn.getInputStream();
FileOutputStream fos = openFileOutput("jing.jpg", MODE_PRIVATE);
int temp=0;
byte[] b=new byte[1024];
while((temp=is.read(b))!=-1){
fos.write(b, 0, temp);
}
is.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("wwwwwwwwwww", "233333");
}else {
Log.e("", "233333");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "加载失败啊!!", 0).show();
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void afterLoad() {
pd.dismiss();
}
}.exe();
//拿到图片地址
return getFilesDir().getAbsolutePath()+"/jing.jpg";
}
private void initView() {
iv = (ImageView) findViewById(R.id.iv);
}
}