製作一個複雜通用的圖片上傳介面
效果圖如下:
首先我們先把圖片載入到記憶體中,這個過程需要壓縮的圖片的尺寸
private class LoadPhotoTask extends AsyncTask<Void, Void, Boolean>{ private Bitmap mLoadedBitmap = null; protected Boolean doInBackground(Void... params) { try { if(mFilePathName.length() > 0){ File file = new File(mFilePathName); if (!file.exists()) { return false; } BitmapFactory.Options opt = new BitmapFactory.Options(); long fileSize = file.length(); int maxSize = 2*1024 * 1024; if(fileSize <= maxSize){ opt.inSampleSize = 1; }else if(fileSize <= maxSize * 4){ opt.inSampleSize = 2; }else{ long times = fileSize / maxSize; opt.inSampleSize = (int)(Math.log(times) / Math.log(2.0)) + 1; } try{ mLoadedBitmap = BitmapFactory.decodeFile(mFilePathName,opt); mUploadFilePathName = SaveBitmapToFile(mLoadedBitmap); }catch(OutOfMemoryError e){ Toast.makeText(UploadPhotoActivity.this, getResources().getString(R.string.no_memory_to_view_photo), Toast.LENGTH_SHORT).show(); UploadPhotoActivity.this.finish(); } } return true; } catch (Exception e) { Log.e("UploadPhotoActivity", "doInBackground", e); return false; } } protected void onPostExecute(Boolean result){ try { showLoadPreviewProgressBar(false); if(mLoadedBitmap != null){ ImageView IamgePreView = (ImageView)findViewById(R.id.photo_upload_preview_image); IamgePreView.setImageBitmap(mLoadedBitmap); }else{ } mLoadedBitmap = null; } catch (Exception e) { Log.e("UploadPhotoActivity", "onPostExecute", e); } } }
因為需要把圖片上傳伺服器,所以我們重新按比例壓縮bitmap,create一個新的bitmap儲存到sd上
private String SaveBitmapToFile(Bitmap bmp){ if (null == bmp) { return null; } String fileName = "upload_tmp.jpg"; File f = this.getFileStreamPath(fileName);//data/data/com.example.tianqitongtest/files/upload_tmp.jpg if (f.exists()) { f.delete(); } FileOutputStream ostream; try { int targetWidth = 780; int w = bmp.getWidth(); if (w > targetWidth) { int h = bmp.getHeight(); int targetHeight = (targetWidth * h) / w; bmp = Bitmap.createScaledBitmap(bmp, targetWidth, targetHeight, true); } ostream = this.openFileOutput(fileName, MODE_PRIVATE); bmp.compress(Bitmap.CompressFormat.JPEG, 70, ostream); ostream.flush(); ostream.close(); ostream = null; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return f.getAbsolutePath(); }
按上傳按鈕的時候,把圖片上傳伺服器
private class UploadPhotoTask extends AsyncTask<String, Void, Boolean>{ protected Boolean doInBackground(String... params) { return HttpUploadedFile.getInstance().doUploadPhoto(getApplicationContext(), mUploadFilePathName, mHandler); } protected void onPostExecute(Boolean result){ mIsUploading = false; showProgressBar(false); if(result){ Toast.makeText(UploadPhotoActivity.this, R.string.upload_photo_fail, Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(UploadPhotoActivity.this, R.string.upload_photo_fail, Toast.LENGTH_SHORT).show(); } } }
上傳圖片的程式碼是:
public boolean doUploadPhoto(Context context, String filePathName, Handler handler) { boolean ret = false; File file = new File(filePathName); if (!file.exists()) { return false; } FileInputStream fs = null; if (file != null) { try { fs = new FileInputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (file == null || fs == null) { return false; } mHandler = handler; ret = postWithoutResponse(context, url, fs, (int) file.length()); if (fs != null) { try { fs.close(); fs = null; } catch (Exception e) { } } return ret; } public Boolean postWithoutResponse(Context context, final String strUrl, InputStream dataStream, int iStreamLen) { if (TextUtils.isEmpty(strUrl) || dataStream == null || iStreamLen <= 0) { lastErrCode = HTTP_ARGUMENT_ERR; return false; } URL postUrl = null; try { postUrl = new URL(strUrl); } catch (MalformedURLException ex) { Log.e("HttpUtil", "get MalformedURL", ex); lastErrCode = HTTP_URL_ERR; return false; } bIsStop = false; InputStream input = null; DataOutputStream ds = null; ByteArrayOutputStream byteOutStream = null; HttpURLConnection conn = null; byte[] outData = null; try { if (bIsStop) { lastErrCode = HTTP_CANCELED; return false; } conn = getConnection(context, postUrl); connection = conn; conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(TIMEOUT * 3); conn.setReadTimeout(TIMEOUT * 3); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Content-Length", String.valueOf(iStreamLen)); if (bIsStop) { lastErrCode = HTTP_CANCELED; return false; } // get the wifi status WifiManager wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); boolean bWifiEnable = (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED); // byte[] data = new byte[BUF_LEN]; ds = new DataOutputStream(conn.getOutputStream()); int len = 0; int postLen = 0; int nMaxProgress = bWifiEnable ? 80 : 40; while (!bIsStop && ((len = dataStream.read(tmpBuf2)) != -1)) { ds.write(tmpBuf2, 0, len); ds.flush(); // waiting for uploading the image file to optimize the progress // bar when using GPRS if (!bWifiEnable) { Thread.sleep(30); } // notify post progress postLen += len; if (mHandler != null) { Message msg = new Message(); msg.what = POST_PROGRESS_NOTIFY; msg.arg1 = (postLen * nMaxProgress) / iStreamLen; mHandler.sendMessage(msg); } } if (bIsStop) { lastErrCode = HTTP_CANCELED; return false; } ds.flush(); // waiting for uploading the image file to optimize the progress bar // when using GPRS if (!bWifiEnable) { postLen = 0; while (postLen < iStreamLen) { Thread.sleep(30); // notify post progress postLen += tmpBuf2.length; if (mHandler != null) { Message msg = new Message(); msg.what = POST_PROGRESS_NOTIFY; msg.arg1 = (postLen * 35) / iStreamLen + 50; mHandler.sendMessage(msg); } } } // waiting for the server's response InputStream is = conn.getInputStream(); int ch; StringBuffer res = new StringBuffer(); while ((ch = is.read()) != -1) { res.append((char) ch); } if (mHandler != null) { Message msg = new Message(); msg.what = POST_PROGRESS_NOTIFY; msg.arg1 = 90; mHandler.sendMessage(msg); } return true; } catch (Exception ex) { Log.e("HttpUtil", "post", ex); if (bIsStop) { lastErrCode = HTTP_CANCELED; } else { lastErrCode = HTTP_EXCEPTION; } return false; } finally { try { outData = null; if (input != null) { input.close(); input = null; } // if (ds != null){ // ds.close(); // ds = null; // } try { ds.close(); ds = null; } catch (Exception e) { // TODO: handle exception } if (conn != null) { conn.disconnect(); conn = null; } if (byteOutStream != null) { byteOutStream.close(); byteOutStream = null; } if (bIsStop) { synchronized (objAbort) { objAbort.notify(); } } if (mHandler != null) { Message msg = new Message(); msg.what = POST_PROGRESS_NOTIFY; msg.arg1 = 100; mHandler.sendMessage(msg); } } catch (Exception ex) { Log.e("HttpUtil", "post finally", ex); } } }
程式碼在
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2144/viewspace-2818549/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 通用mapper、圖片上傳、nginxAPPNginx
- .Net 圖片縮圖上傳通用方法
- VUE:quill修改預設複製圖片base64的行為--富文字複製圖片變成上傳VueUI
- laravel圖片/頭像上傳通用方法Laravel
- Ueditor上傳圖片自動新增水印(通用圖片檔案)
- 用Flask寫一個上傳圖片的APIFlaskAPI
- 線上圖片製作網站哪個好 PS圖片處理教程網站
- canvas 繪製的圖片,進行上傳Canvas
- 分享一個看起來很酷的圖片上傳元件元件
- 通過API介面實現圖片上傳API
- 一個Vue圖片上傳剪裁壓縮元件Vue元件
- 如何製作企業宣傳片:企業宣傳片製作之道
- win10怎麼複製圖片的文字_win10怎樣把圖片上的文字複製下來Win10
- 宣傳片製作技巧
- 給picgo上傳的圖片加個水印PicGo
- 上傳圖片
- 如何實現一個簡易的圖片上傳Web ServerWebServer
- GIF動圖怎麼製作?GIF圖片製作
- Spring Boot MVC 單張圖片和多張圖片上傳 和通用檔案下載Spring BootMVC
- PbootCMS上傳圖片變模糊、上傳圖片尺寸受限的解決方案boot
- 1小時搞定cropper.js製作頭像/圖片上傳、裁剪、併傳送至後端JS後端
- electron上傳圖片
- 上傳圖片jsJS
- 裁剪上傳圖片
- 求一個手機多選上傳圖片的好外掛
- 圖片上傳及圖片處理
- java,springboot + thymeleaf 上傳圖片、刪除圖片到伺服器、本地,壓縮圖片上傳(有些圖片會失真),原圖上傳JavaSpring Boot伺服器
- 電商圖片線上製作,可摳圖可寫文案
- 使用 canvas 繪製圖片,然後下載、上傳Canvas
- 淺談基於uinapp製作一個搞笑圖片生成器UIAPP
- 如何製作一個手機上的Github圖床捷徑(workflow)Github圖床
- js中圖片上傳,多次上傳同一張不生效JS
- PS製作圓角圖片
- 安卓.9圖片製作安卓
- 一個複雜的json例子JSON
- 多圖片formpost上傳ORM
- spring boot 圖片上傳Spring Boot
- 測試圖片上傳