java代码

  1 package com.example.catchlong;  2 import java.io.BufferedOutputStream;  3 import java.io.ByteArrayOutputStream;  4 import java.io.File;  5 import java.io.FileOutputStream;  6 import java.io.IOException;  7 import java.io.InputStream;  8 import java.net.HttpURLConnection;  9 import java.net.URL; 10  11 import android.annotation.SuppressLint; 12 import android.annotation.TargetApi; 13 import android.app.Activity; 14 import android.content.Context; 15 import android.graphics.Bitmap; 16 import android.graphics.BitmapFactory; 17 import android.graphics.Canvas; 18 import android.graphics.Color; 19 import android.graphics.Matrix; 20 import android.graphics.Paint; 21 import android.graphics.PointF; 22 import android.os.Bundle; 23 import android.util.DisplayMetrics; 24 import android.util.FloatMath; 25 import android.util.Log; 26 import android.view.GestureDetector; 27 import android.view.MotionEvent; 28 import android.view.View; 29 import android.view.GestureDetector.OnGestureListener; 30 import android.view.View.OnTouchListener; 31 import android.view.animation.AnimationUtils; 32 import android.widget.ImageView; 33 import android.widget.Toast; 34  35 @SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" }) 36 @TargetApi(5) 37 public class ImageActivity extends Activity implements OnTouchListener { 38     //implements OnTouchListener { 39     private ImageView imgview; 40     private ImageView img; 41   42      43     private Matrix matrix=new Matrix(); 44     private Matrix savedMatrix=new Matrix(); 45      46     static final int NONE = 0;   47     static final int DRAG = 1;   48     static final int ZOOM = 2;   49     int mode = NONE;   50  51     // Remember some things for zooming   52     PointF start = new PointF();   53     PointF mid = new PointF();   54     float oldDist = 1f;   55      56     //private GestureDetector gesture; 57     @Override 58     protected void onCreate(Bundle savedInstanceState) { 59         // TODO Auto-generated method stub 60         super.onCreate(savedInstanceState); 61         this.setContentView(R.layout.imagectrl); 62         imgview=(ImageView)this.findViewById(R.id.imag); 63         downloadImage(); 64         //imgview.setAnimation(AnimationUtils.loadAnimation(this, R.anim.newanim)); 65          66          67         img=(ImageView)this.findViewById(R.id.imag); 68         Matrix mt=img.getImageMatrix();     69         //mt.postRotate(30); 70         mt.postScale(0.5f,0.5f);mt.postScale(1.5f,1.5f); 71         //mt.postRotate(30, 130, 100); 72         mt.postTranslate(100, 10); 73          74         img.setImageMatrix(mt); 75          76      77         //imgview.setLongClickable(true); 78          79         //imgview.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.xieer_1)); 80         imgview.setOnTouchListener(this); 81         imgview.setLongClickable(true); 82          83     } 84     private float spacing(MotionEvent event) {   85         float x = event.getX(0) - event.getX(1);   86         float y = event.getY(0) - event.getY(1);   87         return FloatMath.sqrt(x * x + y * y);   88 }   89  90   91       private void midPoint(PointF point, MotionEvent event) {   92         float x = event.getX(0) + event.getX(1);   93         float y = event.getY(0) + event.getY(1);   94         point.set(x / 2, y / 2);   95 }   96  97     @TargetApi(8) 98     public boolean onTouch(View v, MotionEvent event) { 99         // TODO Auto-generated method stub100         /*101         Log.d("Infor", "类别:"+event.getAction());102         Log.d("Infor", "mask:"+event.getActionMasked());103         Log.d("Infor", "index:"+event.getActionIndex());104         Log.d("Infor", "points:"+event.getPointerCount());*/105         Log.d("Infor", "size:"+event.getSize());106         if(event.getActionMasked()==MotionEvent.ACTION_POINTER_UP)107             Log.d("Infor", "多点操作");108         switch(event.getActionMasked()){109         case MotionEvent.ACTION_DOWN:110               matrix.set(imgview.getImageMatrix());111               savedMatrix.set(matrix);112               start.set(event.getX(),event.getY());113               Log.d("Infor", "触摸了...");114               mode=DRAG;115               break;116         case MotionEvent.ACTION_POINTER_DOWN:  //多点触控117              oldDist=this.spacing(event);118             if(oldDist>10f){119              Log.d("Infor", "oldDist"+oldDist);120              savedMatrix.set(matrix);121              midPoint(mid,event);122              mode=ZOOM;123             }124             break;125         case MotionEvent.ACTION_POINTER_UP:126             mode=NONE;127             break;128         case MotionEvent.ACTION_MOVE:129             if(mode==DRAG){         //此实现图片的拖动功能...130                 matrix.set(savedMatrix);131                 matrix.postTranslate(event.getX()-start.x, event.getY()-start.y);132             }133                 else if(mode==ZOOM){// 此实现图片的缩放功能...134              float newDist=spacing(event);135              if(newDist>10){136                  matrix.set(savedMatrix);137                  float scale=newDist/oldDist;138                  matrix.postScale(scale, scale, mid.x, mid.y);                 139              }140                 }141             break;142         }143         imgview.setImageMatrix(matrix);144         return false;145     }    146     private void downloadImage(){147 148            String filePath= "http://img.jdxi.net/upload/2012/9/201209011610355146.jpg";149 150            @SuppressWarnings("unused")151         String imgName ="liying.jpg";152 153              //使用【方法1】取得的是InputStream,直接从InputStream生成bitmap154 155             try{156 157                 Bitmap bitmap = BitmapFactory.decodeStream(getImageStream(filePath));158 159                 if(bitmap!=null){160 161                     saveFile(bitmap, "liying.jpg");  //调用保存方法162                   163                     String str2 = "/sdcard/mbookyang/liying.jpg";164 165                     File file = new File(str2);166 167                     if(file.exists()){     //判断文件是否存在168 169                         Bitmap bm = BitmapFactory.decodeFile(str2);170                         //由File获取图片并转为Bitmap171 172                        imgview.setImageBitmap(bm);173 174                     }175 176                 }177 178             }179 180             catch(Exception e) {            181                 Toast.makeText(ImageActivity.this,"下载图片失败", Toast.LENGTH_SHORT).show();  182 183                 e.printStackTrace();184 185             }186 187            188 189         }190 191        192 193         //方法1194 195         public InputStream getImageStream(String path)throws Exception{     196 197             URL url = new URL(path);     198 199             HttpURLConnection conn =(HttpURLConnection) url.openConnection();     200 201             conn.setConnectTimeout(5 * 1000);        //设定超时202 203             conn.setRequestMethod("GET");   //GET为下载,POST为上传204 205             if(conn.getResponseCode()== HttpURLConnection.HTTP_OK){     206 207                 return conn.getInputStream();         //获得数据流  208 209             }     210 211             return null;   212 213         } 214 215        216 217         //方法2218 219         public byte[] getImage(String path) throws Exception{     220 221             URL url = new URL(path);     222 223             HttpURLConnection conn =(HttpURLConnection) url.openConnection();     224 225             conn.setConnectTimeout(5 * 1000);   226 227             conn.setRequestMethod("GET");    228 229             InputStream inStream = conn.getInputStream(); 230 231             if(conn.getResponseCode()== HttpURLConnection.HTTP_OK){     232 233                 return readStream(inStream);     234 235             }     236 237             return null;     238 239         }    240 241         public static byte[] readStream(InputStream inStream)throws Exception{     242 243             ByteArrayOutputStream outStream = new ByteArrayOutputStream();     244 245             byte[]buffer =new byte[1024];     246 247             int len =0;     248 249             while((len=inStream.read(buffer)) != -1){     250 251                 outStream.write(buffer, 0, len);     252 253             }     254 255             outStream.close();     256 257             inStream.close();     258 259             return outStream.toByteArray();     260 261         }   262 263        264 265         //保存Bitmap为图片文件266 267         public void saveFile(Bitmap bitmap, String fileName) throws IOException {  268 269             File dirFile = new File("/sdcard/mbookyang");  270 271             if(!dirFile.exists()){  //判断路径是否存在,不存在则创建272 273                 dirFile.mkdir();  274 275             }276 277             File savePath = new File("/sdcard/mbookyang/" + fileName);  //保存路径278 279             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savePath));  280 281             bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);  //质量压缩为80%282 283             bos.flush();  284 285             bos.close();  286 287         }288 289 }

更多相关文章

  1. Android实现读写JSON数据的方法
  2. Android 获取mac地址方法
  3. android videoView播放视频,对播放结束的监听方法
  4. Android 获取本机唯一序列号 和可变UUID方法

随机推荐

  1. Android(安卓)利用程序实现GPS的打开或关
  2. 严苛模式(StrictMode)
  3. Android消息机制(Handler、Looper、Messa
  4. android基础总结篇之九:Intent应用详解
  5. Android模拟器SD卡的使用
  6. Xposed Android(安卓)hook -方法介绍
  7. Activity and Task(一)
  8. Android(安卓)Build Target no Target av
  9. 沉浸式状态栏,无缝换肤,带3D感觉的侧滑菜单
  10. Mac OS X下搭建Android(安卓)Source编译