效果图如下:
首先我们先把图片加载到内存中,这个过程需要压缩的图片的尺寸
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); } } }
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦