Android进阶篇-上传/下载图片

简介:
/**
     * 上传图片到服务器
     * @param uploadFile 要上传的文件目录
     * @param actionUrl 上传的地址
     * @return String
     */
    public static HashMap<String, Object> uploadFile(String actionUrl,Drawable drawable){
      Log.info(TAG, "urlPath= " + actionUrl);
      
      String end ="\r\n";
      String twoHyphens ="--";
      String boundary ="*****";
      
      HttpURLConnection con = null;
      DataOutputStream ds = null;
      InputStream is = null;
      StringBuffer sb = null;
      HashMap<String, Object> map = null;
      
      try{
        URL url =new URL(actionUrl);
        con=(HttpURLConnection)url.openConnection();
        /* 允许Input、Output,不使用Cache */
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        
        /* 设置传送的method=POST */
        con.setRequestMethod("POST");
        /* setRequestProperty */
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
        /* 设置DataOutputStream */
        ds = new DataOutputStream(con.getOutputStream());
        ds.writeBytes(twoHyphens + boundary + end);
        ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file1\";filename=\""+ MyAppActivity.FILENAME +"\""+ end);
        ds.writeBytes(end);  
        
        if(drawable != null){
            Bitmap bitmap = drawableToBitmap(drawable);
            byte[] buffer = Bitmap2Bytes(bitmap);
            ds.write(buffer);
        }
        
        ds.writeBytes(end);
        ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
        /* close streams */
        ds.flush();
        /* 取得Response内容 */
        
        Log.info(TAG, "code= " + con.getResponseCode());
        if(con.getResponseCode() == 200){
            is = con.getInputStream();
            
            int ch;
            sb =new StringBuffer();
            while( ( ch = is.read() ) !=-1 ){
              sb.append( (char)ch );
            }
            ds.close();
            
            Log.info(TAG, "sb= " + sb.toString());
            if(!sb.toString().equals("") || sb.toString() != null){
                 map = new HashMap<String, Object>();
                 map = JsonUtil.parseJSON(sb.toString());
            }
        }
        
      }catch (MalformedURLException e) {
            Log.info("json","url error");
            e.printStackTrace();
        } catch(FileNotFoundException e){
            Log.info("json","file not found");
        }catch (IOException e) {
            Log.info("json","io error");
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try{
                if(ds != null){
                    ds.close();
                }
                if(is != null){
                    is.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        return map;
    }
    
    /**
     * drawable转换为bitamp
     */
    private static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    private static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    
    
    public static void downLoadImage(String urlPath){
        String fileName = urlPath.substring(urlPath.lastIndexOf('/')+1,urlPath.length());//提取下载图片的文件名
        Bitmap bitmap=GetNetBitmap(urlPath);//得到bitmap
        File file = new File(MyAppActivity.DIRPATH);
        if(!file.exists()){
            file.mkdir();
        }    
        
        File file2 = new File(MyAppActivity.DIRPATH,fileName);
        if(!file2.exists()){
            //将网络上读取的图片保存到SDCard中
            try {
                FileOutputStream out=new FileOutputStream(new File(MyAppActivity.DIRPATH, fileName));//为图片文件实例化输出流
                if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){//对图片保存
                    out.flush();
                    Log.info("json","Success");
                    out.close();
                }
            }catch (FileNotFoundException e) {
                // TODO: handle exception
                Log.info("json","文件没发现!!");
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
                Log.info("json","数据流错误!!");
            }
        }
    }
    
    
    /**
     * 取得网络上的图片
     * @param url 图片的URL 
     */
    @SuppressWarnings("unused")
    private static Bitmap GetNetBitmap(String url){
        URL imageUrl = null;
        Bitmap bitmap=null;
        try {
            imageUrl = new URL(url);
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        
        if (imageUrl != null) {
            try {
                HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
                conn.setDoInput(true);// 设置请求的方式
                conn.connect();
                
                InputStream is = conn.getInputStream();// 将得到的数据转化为inputStream
                bitmap = BitmapFactory.decodeStream(is);// 将inputstream转化为Bitmap
                is.close();// 关闭数据
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else{
            Log.info("json", "json is null!!!");
        }
        return bitmap;
    }
    
    /**
     * 上传图片
     * @param uploadFile 要上传的文件目录
     * @param actionUrl 上传的地址
     * @return String
     */
    public static String uploadFile(String uploadFile,String actionUrl){
      String end ="\r\n";
      String twoHyphens ="--";
      String boundary ="*****";
      
      HttpURLConnection con = null;
      DataOutputStream ds = null;
      FileInputStream fStream = null;
      InputStream is = null;
      StringBuffer sb = null;
      
      try{
        URL url =new URL(actionUrl);
        con=(HttpURLConnection)url.openConnection();
        /* 允许Input、Output,不使用Cache */
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        
        /* 设置传送的method=POST */
        con.setRequestMethod("POST");
        /* setRequestProperty */
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
        /* 设置DataOutputStream */
        ds = new DataOutputStream(con.getOutputStream());
        ds.writeBytes(twoHyphens + boundary + end);
        ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file1\";filename=\""+ MyAppActivity.FILENAME +"\""+ end);
        ds.writeBytes(end);  
        /* 取得文件的FileInputStream */
        if(uploadFile != null){
            fStream =new FileInputStream(uploadFile);
            /* 设置每次写入1024bytes */
            int bufferSize =1024;
            byte[] buffer =new byte[bufferSize];
            int length =-1;
            /* 从文件读取数据至缓冲区 */
            while((length = fStream.read(buffer)) !=-1){
              /* 将资料写入DataOutputStream中 */
              ds.write(buffer, 0, length);
            }
        }
        
        ds.writeBytes(end);
        ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
        /* close streams */
        ds.flush();
        /* 取得Response内容 */
        is = con.getInputStream();
        int ch;
        sb =new StringBuffer();
        while( ( ch = is.read() ) !=-1 ){
          sb.append( (char)ch );
        }
        ds.close();
      }catch (MalformedURLException e) {
            Log.info("json","url error");
            e.printStackTrace();
        } catch(FileNotFoundException e){
            Log.info("json","file not found");
        }catch (IOException e) {
            Log.info("json","io error");
            e.printStackTrace();
        }finally{
            try{
                if(ds != null){
                    ds.close();
                }
                if(is != null){
                    is.close();
                }
                if(fStream != null){
                    fStream.close();
                }    
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

相关文章
|
4月前
|
JavaScript 前端开发 Android开发
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
147 13
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
25天前
|
XML Android开发 数据格式
Android利用selector(选择器)实现图片动态点击效果
本文介绍了Android中ImageView的`src`与`background`属性的区别及应用,重点讲解如何通过设置背景选择器实现图片点击动态效果。`src`用于显示原图大小,不拉伸;`background`可随组件尺寸拉伸。通过创建`selector_setting.xml`,结合`setting_press.xml`和`setting_normal.xml`定义按下和正常状态的背景样式,提升用户体验。示例代码展示了具体实现步骤,包括XML配置和形状定义。
Android利用selector(选择器)实现图片动态点击效果
|
25天前
|
Java Android开发
Android图片的手动放大缩小
本文介绍了通过缩放因子实现图片放大缩小的功能,效果如动图所示。关键步骤包括:1) 在布局文件中设置 `android:scaleType=&quot;matrix&quot;`;2) 实例化控件并用 `ScaleGestureDetector` 处理缩放手势;3) 使用 `Matrix` 对图片进行缩放处理。为避免内存崩溃,可在全局配置添加 `android:largeHeap=&quot;true&quot;`。代码中定义了 `beforeScale` 和 `nowScale` 变量控制缩放范围,确保流畅体验。
|
25天前
|
缓存 编解码 Android开发
Android内存优化之图片优化
本文主要探讨Android开发中的图片优化问题,包括图片优化的重要性、OOM错误的成因及解决方法、Android支持的图片格式及其特点。同时介绍了图片储存优化的三种方式:尺寸优化、质量压缩和内存重用,并详细讲解了相关的实现方法与属性。此外,还分析了图片加载优化策略,如异步加载、缓存机制、懒加载等,并结合多级缓存流程提升性能。最后对比了几大主流图片加载框架(Universal ImageLoader、Picasso、Glide、Fresco)的特点与适用场景,重点推荐Fresco在处理大图、动图时的优异表现。这些内容为开发者提供了全面的图片优化解决方案。
|
3月前
|
JavaScript Linux 网络安全
Termux安卓终端美化与开发实战:从下载到插件优化,小白也能玩转Linux
Termux是一款安卓平台上的开源终端模拟器,支持apt包管理、SSH连接及Python/Node.js/C++开发环境搭建,被誉为“手机上的Linux系统”。其特点包括零ROOT权限、跨平台开发和强大扩展性。本文详细介绍其安装准备、基础与高级环境配置、必备插件推荐、常见问题解决方法以及延伸学习资源,帮助用户充分利用Termux进行开发与学习。适用于Android 7+设备,原创内容转载请注明来源。
592 76
|
4月前
|
JavaScript 搜索推荐 Android开发
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
121 8
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
|
4月前
|
数据采集 JavaScript Android开发
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
138 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
10月前
|
Ubuntu 开发工具 Android开发
Repo下载AOSP源码:基于ubuntu22.04 环境配置,android-12.0.0_r32
本文介绍了在基于Ubuntu 22.04的环境下配置Python 3.9、安装repo工具、下载和同步AOSP源码包以及处理repo同步错误的详细步骤。
666 0
Repo下载AOSP源码:基于ubuntu22.04 环境配置,android-12.0.0_r32
|
9月前
|
存储 缓存 编解码
Android经典面试题之图片Bitmap怎么做优化
本文介绍了图片相关的内存优化方法,包括分辨率适配、图片压缩与缓存。文中详细讲解了如何根据不同分辨率放置图片资源,避免图片拉伸变形;并通过示例代码展示了使用`BitmapFactory.Options`进行图片压缩的具体步骤。此外,还介绍了Glide等第三方库如何利用LRU算法实现高效图片缓存。
140 20
Android经典面试题之图片Bitmap怎么做优化