Android中擷取網狀圖片的方法(如果手機緩衝裡面有就從緩衝擷取)

來源:互聯網
上載者:User
最近工作比較閑,除了用公司的imac機學學iphone外,有必要對以前的項目裡面的痛點進行一下總結了,對於Android開發中的痛點,一是網路擷取內容的處理,二是UI設計方面。對於我來說,特別麻煩就是UI設計方面的東西,公司的開發以iphone為主,畢竟香港人的iphone普及比較高(銷售價格好像是全球最低的),為了模仿iphone的Tabbar,用TabActivity+ActivityGroup的處理方式不知道出了多少問題了,還好都一一解決了。 

   擷取網狀圖片的方法(如果手機緩衝裡面有就從緩衝擷取),我以前寫的,比較原始:

ImageView mImageView = (ImageView)this.findViewById(R.id.imageview);String imagePath = getImagePath(context, photoURL); // context:上下文 ,photoURL:圖片的url路徑mImageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));

// 擷取網狀圖片,如果緩衝裡面有就從緩衝裡面擷取public static  String getImagePath(Context context, String url) {if(url == null )return "";String imagePath = "";String   fileName   = "";// 擷取url中圖片的檔案名稱與尾碼if(url!=null&&url.length()!=0){ fileName  = url.substring(url.lastIndexOf("/")+1);}// 圖片在手機本地的存放路徑,注意:fileName為空白的情況imagePath = context.getCacheDir() + "/" + fileName;Log.i(TAG,"imagePath = " + imagePath);File file = new File(context.getCacheDir(),fileName);// 儲存檔案,if(!file.exists()){Log.i(TAG, "file 不存在 ");try {byte[] data =  readInputStream(getRequest(url));Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));imagePath = file.getAbsolutePath();Log.i(TAG,"imagePath : file.getAbsolutePath() = " +  imagePath);} catch (Exception e) {Log.e(TAG, e.toString());}}return imagePath;} // getImagePath( )結束。

public static InputStream getRequest(String path) throws Exception{    URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5000); // 5秒if(conn.getResponseCode() == 200){return conn.getInputStream();}return null;}

public static byte[] readInputStream(InputStream inStream) throws Exception{        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();        byte[] buffer = new byte[4096];        int len = 0;        while( (len = inStream.read(buffer)) != -1 ){            outSteam.write(buffer, 0, len);        }        outSteam.close();        inStream.close();        return outSteam.toByteArray();}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.