zoukankan      html  css  js  c++  java
  • android 下载图片保存在sdcard并显示可拖动缩放

    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 stub
    100         /*
    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生成bitmap
    154 
    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获取图片并转为Bitmap
    171 
    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         //方法1
    194 
    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         //方法2
    218 
    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 }
  • 相关阅读:
    网络密钥交换协议——Diffie-Hellman
    【剑指Offer】俯视50题之1-10题
    分治
    《Java程序猿面试笔试宝典》之Java程序初始化的顺序是如何的
    China Final J
    MVC入门
    1,单例模式
    运行耗时统计
    普通方法调用,Invoke,begininvoke三者的区别总结及异步与同步的区别总结
    几种查询方法(lambda Linq Enumerable静态类方式)
  • 原文地址:https://www.cnblogs.com/yema/p/2673643.html
Copyright © 2011-2022 走看看