Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發實戰(二十五):自訂圖片裁剪與頭像設定

編輯:關於 Android 開發

很早以前就看到朋友在討論 QQ 頭像的裁剪上傳是怎麼做的,一直好奇,趁這次機會自己也動手試了試。翻了一下舊專案,發現裡頭有類似的功能,再對照官方文件裡的說明,玩起來就更上手了。

今天一邊聽著《變3》的主題曲,一邊把編程過程重新記錄下來,希望能和更多朋友交流學習。文中截圖本想做成動態的,無奈 WordPress 和 Jekyll 似乎都不太支援 Gif,想看動態效果的朋友可以到 51CTO 那邊瀏覽:https://mzh3344258.blog.51cto.com/blog/1823534/808837。如果覺得有用,也歡迎分享出去,讓更多開發的朋友受益。

同樣的,先看效果圖,再看程式碼怎麼實現。以下都是在模擬器裡完成的,真機上也能正常運行,因為功能其實很簡單。

一、主介面

二、點擊控制項觸發事件後

三、拍照完成後

四、裁剪介面

五、從相簿返回的圖片

六、相簿 PICK 裁剪保存後的效果

下面直接來看主控制類的程式碼:

Java 程式碼:

  1. package com.xiaoma.piccut.demo;
  2. import java.io.File;
  3. import android.app.Activity;
  4. import android.app.AlertDialog;
  5. import android.content.DialogInterface;
  6. import android.content.Intent;
  7. import android.graphics.Bitmap;
  8. import android.graphics.drawable.BitmapDrawable;
  9. import android.graphics.drawable.Drawable;
  10. import android.net.Uri;
  11. import android.os.Bundle;
  12. import android.os.Environment;
  13. import android.provider.MediaStore;
  14. import android.view.View;
  15. import android.view.View.OnClickListener;
  16. import android.widget.Button;
  17. import android.widget.ImageButton;
  18. import android.widget.ImageView;
  19. /**
  20. * @Title: PicCutDemoActivity.java
  21. * @Package com.xiaoma.piccut.demo
  22. * @Description: 圖片裁剪功能測試
  23. * @author XiaoMa
  24. */
  25. public class PicCutDemoActivity extends Activity implements OnClickListener {
  26. private ImageButton ib = null;
  27. private ImageView iv = null;
  28. private Button btn = null;
  29. private String tp = null;
  30. /** Called when the activity is first created. */
  31. @Override
  32. public void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.main);
  35. //初始化
  36. init();
  37. }
  38. /**
  39. * 初始化方法實現
  40. */
  41. private void init() {
  42. ib = (ImageButton) findViewById(R.id.imageButton1);
  43. iv = (ImageView) findViewById(R.id.imageView1);
  44. btn = (Button) findViewById(R.id.button1);
  45. ib.setOnClickListener(this);
  46. iv.setOnClickListener(this);
  47. btn.setOnClickListener(this);
  48. }
  49. /**
  50. * 控件點擊事件實現
  51. *
  52. * 因為有朋友問不同控件的背景圖裁剪怎麼實現,
  53. * 我就在這個地方用了三個控件,只為了自己記錄學習
  54. * 大家覺得沒用的可以跳過啦
  55. */
  56. @Override
  57. public void onClick(View v) {
  58. switch (v.getId()) {
  59. case R.id.imageButton1:
  60. ShowPickDialog();
  61. break;
  62. case R.id.imageView1:
  63. ShowPickDialog();
  64. break;
  65. case R.id.button1:
  66. ShowPickDialog();
  67. break;
  68. default:
  69. break;
  70. }
  71. }
  72. /**
  73. * 選擇提示對話框
  74. */
  75. private void ShowPickDialog() {
  76. new AlertDialog.Builder(this)
  77. .setTitle("設置頭像...")
  78. .setNegativeButton("相冊", new DialogInterface.OnClickListener() {
  79. public void onClick(DialogInterface dialog, int which) {
  80. dialog.dismiss();
  81. /**
  82. * 剛開始,我自己也不知道ACTION_PICK是干嘛的,後來直接看Intent源碼,
  83. * 可以發現裡面很多東西,Intent是個很強大的東西,大家一定仔細閱讀下
  84. */
  85. Intent intent = new Intent(Intent.ACTION_PICK, null);
  86. /**
  87. * 下面這句話,與其它方式寫是一樣的效果,如果:
  88. * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  89. * intent.setType(""image/*");設置數據類型
  90. * 如果朋友們要限制上傳到服務器的圖片類型時可以直接寫如:"image/jpeg 、 image/png等的類型"
  91. * 這個地方小馬有個疑問,希望高手解答下:就是這個數據URI與類型為什麼要分兩種形式來寫呀?有什麼區別?
  92. */
  93. intent.setDataAndType(
  94. MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
  95. "image/*");
  96. startActivityForResult(intent, 1);
  97. }
  98. })
  99. .setPositiveButton("拍照", new DialogInterface.OnClickListener() {
  100. public void onClick(DialogInterface dialog, int whichButton) {
  101. dialog.dismiss();
  102. /**
  103. * 下面這句還是老樣子,調用快速拍照功能,至於為什麼叫快速拍照,大家可以參考如下官方
  104. * 文檔,you_sdk_path/docs/guide/topics/media/camera.html
  105. * 我剛看的時候因為太長就認真看,其實是錯的,這個裡面有用的太多了,所以大家不要認為
  106. * 官方文檔太長了就不看了,其實是錯的,這個地方小馬也錯了,必須改正
  107. */
  108. Intent intent = new Intent(
  109. MediaStore.ACTION_IMAGE_CAPTURE);
  110. //下面這句指定調用相機拍照後的照片存儲的路徑
  111. intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
  112. .fromFile(new File(Environment
  113. .getExternalStorageDirectory(),
  114. "xiaoma.jpg")));
  115. startActivityForResult(intent, 2);
  116. }
  117. }).show();
  118. }
  119. @Override
  120. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  121. switch (requestCode) {
  122. // 如果是直接從相冊獲取
  123. case 1:
  124. startPhotoZoom(data.getData());
  125. break;
  126. // 如果是調用相機拍照時
  127. case 2:
  128. File temp = new File(Environment.getExternalStorageDirectory()
  129. + "/xiaoma.jpg");
  130. startPhotoZoom(Uri.fromFile(temp));
  131. break;
  132. // 取得裁剪後的圖片
  133. case 3:
  134. /**
  135. * 非空判斷大家一定要驗證,如果不驗證的話,
  136. * 在剪裁之後如果發現不滿意,要重新裁剪,丟棄
  137. * 當前功能時,會報NullException,小馬只
  138. * 在這個地方加下,大家可以根據不同情況在合適的
  139. * 地方做判斷處理類似情況
  140. *
  141. */
  142. if(data != null){
  143. setPicToView(data);
  144. }
  145. break;
  146. default:
  147. break;
  148. }
  149. super.onActivityResult(requestCode, resultCode, data);
  150. }
  151. /**
  152. * 裁剪圖片方法實現
  153. * @param uri
  154. */
  155. public void startPhotoZoom(Uri uri) {
  156. /*
  157. * 至於下面這個Intent的ACTION是怎麼知道的,大家可以看下自己路徑下的如下網頁
  158. * yourself_sdk_path/docs/reference/android/content/Intent.html
  159. * 直接在裡面Ctrl+F搜:CROP ,之前小馬沒仔細看過,其實安卓系統早已經有自帶圖片裁剪功能,
  160. * 是直接調本地庫的,小馬不懂C C++ 這個不做詳細了解去了,有輪子就用輪子,不再研究輪子是怎麼
  161. * 制做的了...吼吼
  162. */
  163. Intent intent = new Intent("com.android.camera.action.CROP");
  164. intent.setDataAndType(uri, "image/*");
  165. //下面這個crop=true是設置在開啟的Intent中設置顯示的VIEW可裁剪
  166. intent.putExtra("crop", "true");
  167. // aspectX aspectY 是寬高的比例
  168. intent.putExtra("aspectX", 1);
  169. intent.putExtra("aspectY", 1);
  170. // outputX outputY 是裁剪圖片寬高
  171. intent.putExtra("outputX", 150);
  172. intent.putExtra("outputY", 150);
  173. intent.putExtra("return-data", true);
  174. startActivityForResult(intent, 3);
  175. }
  176. /**
  177. * 保存裁剪之後的圖片數據
  178. * @param picdata
  179. */
  180. private void setPicToView(Intent picdata) {
  181. Bundle extras = picdata.getExtras();
  182. if (extras != null) {
  183. Bitmap photo = extras.getParcelable("data");
  184. Drawable drawable = new BitmapDrawable(photo);
  185. /**
  186. * 下面注釋的方法是將裁剪之後的圖片以Base64Coder的字符方式上
  187. * 傳到服務器,QQ頭像上傳采用的方法跟這個類似
  188. */
  189. /*ByteArrayOutputStream stream = new ByteArrayOutputStream();
  190. photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
  191. byte[] b = stream.toByteArray();
  192. // 將圖片流以字符串形式存儲下來
  193. tp = new String(Base64Coder.encodeLines(b));
  194. /**這個地方大家可以寫下給服務器上傳圖片的實現,直接把tp直接上傳就可以了,
  195. *服務器處理的方法是服務器那邊的事了,吼吼
  196. *如果下載到的服務器的數據還是以Base64Coder的形式的話,可以用以下方式轉換
  197. *為我們可以用的圖片類型就OK啦...吼吼 */
  198. Bitmap dBitmap = BitmapFactory.decodeFile(tp);
  199. Drawable drawable = new BitmapDrawable(dBitmap);
  200. */
  201. ib.setBackgroundDrawable(drawable);
  202. iv.setBackgroundDrawable(drawable);
  203. }
  204. }
  205. }

接著看看裁剪中用到的 Base64Coder 類,請留意頭部的註解,裡頭其實是一份 license 聲明,需要的朋友可以前往對應網址選用合適的授權條款:

Java 程式碼:

  1. package com.xiaoma.piccut.demo;
  2. /**
  3. * 下面這些注釋是下載這個類的時候本來就有的,本來要刪除的,但看了下竟然是license,吼吼,
  4. * 好東西,留在注釋裡,以備不時之用,大家有需要加license的可以到下面的網址找哦
  5. */
  6. //EPL, Eclipse Public License, V1.0 or later, https://www.eclipse.org/legal
  7. //LGPL, GNU Lesser General Public License, V2.1 or later, https://www.gnu.org/licenses/lgpl.html
  8. //GPL, GNU General Public License, V2 or later, https://www.gnu.org/licenses/gpl.html
  9. //AL, Apache License, V2.0 or later, https://www.apache.org/licenses
  10. //BSD, BSD License, https://www.opensource.org/licenses/bsd-license.php
  11. /**
  12. * A Base64 encoder/decoder.
  13. *
  14. * <p>
  15. * This class is used to encode and decode data in Base64 format as described in RFC 1521.
  16. *
  17. * <p>
  18. * Project home page: <a href="https://www.source-code.biz/base64coder/java/">www.source-code.biz/base64coder/java</a><br>
  19. * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
  20. * Multi-licensed: EPL / LGPL / GPL / AL / BSD.
  21. */
  22. /**
  23. * 這個類在上面注釋的網址中有,大家可以自行下載下,也可以直接用這個,
  24. * 公開的Base64Coder類(不用深究它是怎麼實現的,
  25. * 還是那句話,有輪子直接用輪子),好用的要死人了...
  26. * 小馬也很無恥的引用了這個網址下的東東,吼吼...
  27. * @Title: Base64Coder.java
  28. * @Package com.xiaoma.piccut.demo
  29. * @Description: TODO
  30. * @author XiaoMa
  31. */
  32. public class Base64Coder {
  33. //The line separator string of the operating system.
  34. private static final String systemLineSeparator = System.getProperty("line.separator");
  35. //Mapping table from 6-bit nibbles to Base64 characters.
  36. private static char[] map1 = new char[64];
  37. static {
  38. int i=0;
  39. for (char c='A'; c<='Z'; c++) map1[i++] = c;
  40. for (char c='a'; c<='z'; c++) map1[i++] = c;
  41. for (char c='0'; c<='9'; c++) map1[i++] = c;
  42. map1[i++] = '+'; map1[i++] = '/'; }
  43. //Mapping table from Base64 characters to 6-bit nibbles.
  44. private static byte[] map2 = new byte[128];
  45. static {
  46. for (int i=0; i<map2.length; i++) map2[i] = -1;
  47. for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; }
  48. /**
  49. * Encodes a string into Base64 format.
  50. * No blanks or line breaks are inserted.
  51. * @param s A String to be encoded.
  52. * @return A String containing the Base64 encoded data.
  53. */
  54. public static String encodeString (String s) {
  55. return new String(encode(s.getBytes())); }
  56. /**
  57. * Encodes a byte array into Base 64 format and breaks the output into lines of 76 characters.
  58. * This method is compatible with <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>.
  59. * @param in An array containing the data bytes to be encoded.
  60. * @return A String containing the Base64 encoded data, broken into lines.
  61. */
  62. public static String encodeLines (byte[] in) {
  63. return encodeLines(in, 0, in.length, 76, systemLineSeparator); }
  64. /**
  65. * Encodes a byte array into Base 64 format and breaks the output into lines.
  66. * @param in An array containing the data bytes to be encoded.
  67. * @param iOff Offset of the first byte in <code>in</code> to be processed.
  68. * @param iLen Number of bytes to be processed in <code>in</code>, starting at <code>iOff</code>.
  69. * @param lineLen Line length for the output data. Should be a multiple of 4.
  70. * @param lineSeparator The line separator to be used to separate the output lines.
  71. * @return A String containing the Base64 encoded data, broken into lines.
  72. */
  73. public static String encodeLines (byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) {
  74. int blockLen = (lineLen*3) / 4;
  75. if (blockLen <= 0) throw new IllegalArgumentException();
  76. int lines = (iLen+blockLen-1) / blockLen;
  77. int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length();
  78. StringBuilder buf = new StringBuilder(bufLen);
  79. int ip = 0;
  80. while (ip < iLen) {
  81. int l = Math.min(iLen-ip, blockLen);
  82. buf.append (encode(in, iOff+ip, l));
  83. buf.append (lineSeparator);
  84. ip += l; }
  85. return buf.toString(); }
  86. /**
  87. * Encodes a byte array into Base64 format.
  88. * No blanks or line breaks are inserted in the output.
  89. * @param in An array containing the data bytes to be encoded.
  90. * @return A character array containing the Base64 encoded data.
  91. */
  92. public static char[] encode (byte[] in) {
  93. return encode(in, 0, in.length); }
  94. /**
  95. * Encodes a byte array into Base64 format.
  96. * No blanks or line breaks are inserted in the output.
  97. * @param in An array containing the data bytes to be encoded.
  98. * @param iLen Number of bytes to process in <code>in</code>.
  99. * @return A character array containing the Base64 encoded data.
  100. */
  101. public static char[] encode (byte[] in, int iLen) {
  102. return encode(in, 0, iLen); }
  103. /**
  104. * Encodes a byte array into Base64 format.
  105. * No blanks or line breaks are inserted in the output.
  106. * @param in An array containing the data bytes to be encoded.
  107. * @param iOff Offset of the first byte in <code>in</code> to be processed.
  108. * @param iLen Number of bytes to process in <code>in</code>, starting at <code>iOff</code>.
  109. * @return A character array containing the Base64 encoded data.
  110. */
  111. public static char[] encode (byte[] in, int iOff, int iLen) {
  112. int oDataLen = (iLen*4+2)/3; // output length without padding
  113. int oLen = ((iLen+2)/3)*4; // output length including padding
  114. char[] out = new char[oLen];
  115. int ip = iOff;
  116. int iEnd = iOff + iLen;
  117. int op = 0;
  118. while (ip < iEnd) {
  119. int i0 = in[ip++] & 0xff;
  120. int i1 = ip < iEnd ? in[ip++] & 0xff : 0;
  121. int i2 = ip < iEnd ? in[ip++] & 0xff : 0;
  122. int o0 = i0 >>> 2;
  123. int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
  124. int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
  125. int o3 = i2 & 0x3F;
  126. out[op++] = map1[o0];
  127. out[op++] = map1[o1];
  128. out[op] = op < oDataLen ? map1[o2] : '='; op++;
  129. out[op] = op < oDataLen ? map1[o3] : '='; op++; }
  130. return out; }
  131. /**
  132. * Decodes a string from Base64 format.
  133. * No blanks or line breaks are allowed within the Base64 encoded input data.
  134. * @param s A Base64 String to be decoded.
  135. * @return A String containing the decoded data.
  136. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  137. */
  138. public static String decodeString (String s) {
  139. return new String(decode(s)); }
  140. /**
  141. * Decodes a byte array from Base64 format and ignores line separators, tabs and blanks.
  142. * CR, LF, Tab and Space characters are ignored in the input data.
  143. * This method is compatible with <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>.
  144. * @param s A Base64 String to be decoded.
  145. * @return An array containing the decoded data bytes.
  146. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  147. */
  148. public static byte[] decodeLines (String s) {
  149. char[] buf = new char[s.length()+3];
  150. int p = 0;
  151. for (int ip = 0; ip < s.length(); ip++) {
  152. char c = s.charAt(ip);
  153. if (c != ' ' && c != '\r' && c != '\n' && c != '\t')
  154. buf[p++] = c; }
  155. while ((p % 4) != 0)
  156. buf[p++] = '0';
  157. return decode(buf, 0, p); }
  158. /**
  159. * Decodes a byte array from Base64 format.
  160. * No blanks or line breaks are allowed within the Base64 encoded input data.
  161. * @param s A Base64 String to be decoded.
  162. * @return An array containing the decoded data bytes.
  163. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  164. */
  165. public static byte[] decode (String s) {
  166. return decode(s.toCharArray()); }
  167. /**
  168. * Decodes a byte array from Base64 format.
  169. * No blanks or line breaks are allowed within the Base64 encoded input data.
  170. * @param in A character array containing the Base64 encoded data.
  171. * @return An array containing the decoded data bytes.
  172. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  173. */
  174. public static byte[] decode (char[] in) {
  175. return decode(in, 0, in.length); }
  176. /**
  177. * Decodes a byte array from Base64 format.
  178. * No blanks or line breaks are allowed within the Base64 encoded input data.
  179. * @param in A character array containing the Base64 encoded data.
  180. * @param iOff Offset of the first character in <code>in</code> to be processed.
  181. * @param iLen Number of characters to process in <code>in</code>, starting at <code>iOff</code>.
  182. * @return An array containing the decoded data bytes.
  183. * @throws IllegalArgumentException If the input is not valid Base64 encoded data.
  184. */
  185. public static byte[] decode (char[] in, int iOff, int iLen) {
  186. if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4.");
  187. while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--;
  188. int oLen = (iLen*3) / 4;
  189. byte[] out = new byte[oLen];
  190. int ip = iOff;
  191. int iEnd = iOff + iLen;
  192. int op = 0;
  193. while (ip < iEnd) {
  194. int i0 = in[ip++];
  195. int i1 = in[ip++];
  196. int i2 = ip < iEnd ? in[ip++] : 'A';
  197. int i3 = ip < iEnd ? in[ip++] : 'A';
  198. if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
  199. throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
  200. int b0 = map2[i0];
  201. int b1 = map2[i1];
  202. int b2 = map2[i2];
  203. int b3 = map2[i3];
  204. if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
  205. throw new IllegalArgumentException ("Illegal character in Base64 encoded data.");
  206. int o0 = ( b0 <<2) | (b1>>>4);
  207. int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
  208. int o2 = ((b2 & 3)<<6) | b3;
  209. out[op++] = (byte)o0;
  210. if (op<oLen) out[op++] = (byte)o1;
  211. if (op<oLen) out[op++] = (byte)o2; }
  212. return out; }
  213. //Dummy constructor.
  214. private Base64Coder() {}
  215. } // end class Base64Coder

最後,小 DEMO 源碼可在此下載:https://mzh3344258.blog.51cto.com/blog/1823534/808837(頁面最下方的 Demo 源碼即是),有需要的朋友歡迎下載,一起交流學習。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved