当前位置:   article > 正文

android小文章——手机照片上传服务器方法_安卓在图库选择图片后上传php

安卓在图库选择图片后上传php

话不多说,直接上代码

客户端代码:

客户端Activity中要获取到选择的图片数据方法

  1. //照相机照照片后回调数据的接收并赋值给全局的data变量
  2. ImageCameraActivity.setIMGcallback(new IMGCallBack() {
  3.     public void callback(String data) {
  4.         this.data = data;
  5.         //this.data 中 data为Activity中的全局变量,是用来提交到服务器的加密过的图片的String数据
  6.     }
  7. });
  8. //相册选择图片后回调数据的接收并赋值给全局的data变量
  9. ImagePhotoActivity.setIMGcallback(new IMGCallBack1() {
  10.     public void callback(String data) {
  11.         this.data = data;
  12.     //this.data 中 data为Activity中的全局变量,是用来提交到服务器的加密过的图片的String数据            
  13.     }
  14. });

接下来就是点击按钮打开选择图片或者相机的方法了

直接在Activity中启动下面的方法中的Activity即可

  1. Intent intent = new Intent(getApplicationContext(),ImageCameraActivity.class);
  2. startActivity(intent);
  3. Intent intent = new Intent(getApplicationContext(),ImagePhotoActivity.class);
  4. startActivity(intent);

1、通过图库选择照片上传到服务器

  1. import java.io.ByteArrayOutputStream;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import android.app.Activity;
  5. import android.content.ContentResolver;
  6. import android.content.Intent;
  7. import android.graphics.Bitmap;
  8. import android.graphics.Bitmap.CompressFormat;
  9. import android.graphics.BitmapFactory;
  10. import android.graphics.Matrix;
  11. import android.media.ExifInterface;
  12. import android.net.Uri;
  13. import android.os.Bundle;
  14. import android.util.Base64;
  15. import android.view.Window;
  16. import android.widget.Toast;
  17. /**
  18. * 图库界面
  19. * @author 苦涩
  20. * 联系QQ:534429149
  21. * */
  22. public class ImagePhotoActivity extends Activity {
  23. private Bitmap bm = null;
  24. private String Tag = "ImgAct";
  25. private Intent date = null;
  26. Uri uri = null;
  27. String sdStatus = null;
  28. boolean isstate = true;
  29. private static IMGCallBack1 mIMGCallBack;
  30. @Override
  31. protected void onCreate(Bundle savedInstanceState) {
  32. requestWindowFeature(Window.FEATURE_NO_TITLE);
  33. super.onCreate(savedInstanceState);
  34. Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
  35. intent.addCategory(Intent.CATEGORY_OPENABLE);
  36. intent.setType("image/*");
  37. intent.putExtra("return-data", true);
  38. startActivityForResult(intent, 0);
  39. }
  40. @Override
  41. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  42. super.onActivityResult(requestCode, resultCode, data);
  43. ContentResolver resolver = getContentResolver();
  44. if (requestCode == 0) {
  45. date = data;
  46. if (date != null) {
  47. Uri originalUri = data.getData(); // 获得图片的uri
  48. if (originalUri.getPath().toString() != null) {
  49. try {
  50. BitmapFactory.Options options = new BitmapFactory.Options();
  51. options.inSampleSize = 1;
  52. options.inPreferredConfig = Bitmap.Config.RGB_565;
  53. options.inPurgeable = true;
  54. options.inInputShareable = true;
  55. if (null != bm && bm.isRecycled() == false) {
  56. bm.recycle();
  57. }
  58. bm = BitmapFactory.decodeStream(resolver
  59. .openInputStream(Uri.parse(originalUri
  60. .toString())), null, options);
  61. } catch (Exception e) {
  62. e.printStackTrace();
  63. } // 显得到bitmap图片
  64. if (bm != null) {
  65. new MyCamaralThread().start();
  66. } else {
  67. Toast.makeText(ImagePhotoActivity.this, "图片获取失败", 1)
  68. .show();
  69. }
  70. } else {
  71. Toast.makeText(ImagePhotoActivity.this, "图片获取失败", 1).show();
  72. }
  73. } else {
  74. ImagePhotoActivity.this.finish();
  75. }
  76. }
  77. }
  78. /****************** 解决图片旋转问题 ****************************/
  79. public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
  80. // 旋转图片 动作
  81. Matrix matrix = new Matrix();
  82. ;
  83. matrix.postRotate(angle);
  84. // 创建新的图片
  85. Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
  86. bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  87. return resizedBitmap;
  88. }
  89. /**
  90. * 读取图片属性:旋转的角度
  91. *
  92. * @param path
  93. * 图片绝对路径
  94. * @return degree旋转的角度
  95. */
  96. public static int readPictureDegree(String path) {
  97. int degree = 0;
  98. try {
  99. ExifInterface exifInterface = new ExifInterface(path);
  100. int orientation = exifInterface.getAttributeInt(
  101. ExifInterface.TAG_ORIENTATION,
  102. ExifInterface.ORIENTATION_NORMAL);
  103. switch (orientation) {
  104. case ExifInterface.ORIENTATION_ROTATE_90:
  105. degree = 90;
  106. break;
  107. case ExifInterface.ORIENTATION_ROTATE_180:
  108. degree = 180;
  109. break;
  110. case ExifInterface.ORIENTATION_ROTATE_270:
  111. degree = 270;
  112. break;
  113. }
  114. } catch (IOException e) {
  115. e.printStackTrace();
  116. }
  117. return degree;
  118. }
  119. /**********************************************/
  120. File fial = null;
  121. class MyCamaralThread extends Thread {
  122. public void run() {
  123. float mWeight = 480f;
  124. float mHight = 854f;
  125. float scaleWidth;
  126. float scaleHeight;
  127. scaleWidth = ((float) mWeight) / bm.getWidth();
  128. scaleHeight = ((float) mHight) / bm.getHeight();
  129. Matrix matrix = new Matrix();
  130. // matrix.postScale(scaleWidth, scaleHeight);
  131. matrix.postScale(0.3f, 0.3f);//压缩比例,不希望压缩的话就改成1,1
  132. Bitmap mbit = null;
  133. mbit = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(),
  134. matrix, true);
  135. ByteArrayOutputStream bStream = new ByteArrayOutputStream();
  136. mbit.compress(CompressFormat.PNG, 50, bStream);
  137. byte[] bytes = bStream.toByteArray();
  138. String data = Base64.encodeToString(bytes, Base64.DEFAULT);
  139. if (mIMGCallBack != null) {
  140. mIMGCallBack.callback(data);
  141. }
  142. ImagePhotoActivity.this.finish();
  143. }
  144. }
  145. public static void setIMGcallback(IMGCallBack1 myIMGCallBack) {
  146. mIMGCallBack = myIMGCallBack;
  147. }
  148. public interface IMGCallBack1 {
  149. public void callback(String data);
  150. }
  151. }


2、通过照相机照相然后上传到服务器

  1. import java.io.ByteArrayOutputStream;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import android.app.Activity;
  5. import android.content.Intent;
  6. import android.graphics.Bitmap;
  7. import android.graphics.Bitmap.CompressFormat;
  8. import android.graphics.BitmapFactory;
  9. import android.graphics.Matrix;
  10. import android.media.ExifInterface;
  11. import android.net.Uri;
  12. import android.os.Bundle;
  13. import android.os.Environment;
  14. import android.provider.MediaStore;
  15. import android.util.Base64;
  16. import android.util.Log;
  17. import android.widget.Toast;
  18. /**
  19. * 拍照界面
  20. * @author 苦涩
  21. * 联系QQ:534429149
  22. * */
  23. public class ImageCameraActivity extends Activity {
  24. private Bitmap bitmap;
  25. String imgPath = "/sdcard/img.jpg";
  26. Uri uri = null;
  27. String sdStatus = null;
  28. boolean isstate = true;
  29. private static IMGCallBack mIMGCallBack;
  30. @Override
  31. protected void onCreate(Bundle savedInstanceState) {
  32. super.onCreate(savedInstanceState);
  33. sdStatus = Environment.getExternalStorageState();
  34. if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
  35. Log.d("CameralAct",
  36. "if (!sdStatus.equals(Environment.MEDIA_MOUNTED)");
  37. isstate = false;
  38. Intent it = new Intent("android.media.action.IMAGE_CAPTURE");
  39. startActivityForResult(it, Activity.DEFAULT_KEYS_DIALER);
  40. } else {
  41. Log.d("CameralAct",
  42. "if (sdStatus.equals(Environment.MEDIA_MOUNTED)");
  43. isstate = true;
  44. File vFile = new File(imgPath);
  45. if (!vFile.exists()) {
  46. File vDirPath = vFile.getParentFile(); // new
  47. // File(vFile.getParent());
  48. vDirPath.mkdirs();
  49. }
  50. Uri uri = Uri.fromFile(vFile);
  51. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  52. intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//
  53. startActivityForResult(intent, 0);
  54. }
  55. }
  56. /****************** 解决图片旋转问题 ****************************/
  57. public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
  58. // 旋转图片 动作
  59. Matrix matrix = new Matrix();
  60. ;
  61. matrix.postRotate(angle);
  62. // 创建新的图片
  63. Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
  64. bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  65. return resizedBitmap;
  66. }
  67. /**
  68. * 读取图片属性:旋转的角度
  69. *
  70. * @param path
  71. * 图片绝对路径
  72. * @return degree旋转的角度
  73. */
  74. public static int readPictureDegree(String path) {
  75. int degree = 0;
  76. try {
  77. // 读取图片属性的
  78. ExifInterface exifInterface = new ExifInterface(path);
  79. int orientation = exifInterface.getAttributeInt(
  80. ExifInterface.TAG_ORIENTATION,
  81. ExifInterface.ORIENTATION_NORMAL);
  82. switch (orientation) {
  83. case ExifInterface.ORIENTATION_ROTATE_90:
  84. degree = 90;
  85. break;
  86. case ExifInterface.ORIENTATION_ROTATE_180:
  87. degree = 180;
  88. break;
  89. case ExifInterface.ORIENTATION_ROTATE_270:
  90. degree = 270;
  91. break;
  92. }
  93. } catch (IOException e) {
  94. e.printStackTrace();
  95. }
  96. return degree;
  97. }
  98. /**********************************************/
  99. File fial = null;
  100. @Override
  101. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  102. super.onActivityResult(requestCode, resultCode, data);
  103. if (isstate && resultCode == Activity.RESULT_OK) {
  104. fial = new File(imgPath);
  105. uri = Uri.fromFile(fial);
  106. // 设置图片对应属性(压缩图片)
  107. BitmapFactory.Options options = new BitmapFactory.Options();
  108. options.inSampleSize = 2;
  109. options.inPreferredConfig = Bitmap.Config.RGB_565;
  110. options.inPurgeable = true;
  111. options.inInputShareable = true;
  112. int degree = readPictureDegree(fial.getAbsolutePath());
  113. if (null != bitmap && bitmap.isRecycled() == false) {
  114. bitmap.recycle();
  115. bitmap = null;
  116. }
  117. if (uri != null) {
  118. bitmap = BitmapFactory.decodeFile(uri.getPath(), options);
  119. bitmap = rotaingImageView(degree,
  120. BitmapFactory.decodeFile(uri.getPath(), options));
  121. }
  122. // 保存图片到本地
  123. if (bitmap != null) {
  124. new MyCamaralThread().start();
  125. } else {
  126. Toast.makeText(getApplicationContext(), "照片获取失败", 1).show();
  127. ImageCameraActivity.this.finish();
  128. }
  129. return;
  130. } else if (!isstate) {
  131. new MyCamaralThread().start();
  132. if (data != null) {
  133. Uri uri = data.getData();
  134. if (null != uri || uri.getPath() != null) {
  135. try {
  136. BitmapFactory.Options options = new BitmapFactory.Options();
  137. options.inSampleSize = 2;
  138. options.inPreferredConfig = Bitmap.Config.RGB_565;
  139. options.inPurgeable = true;
  140. options.inInputShareable = true;
  141. if (null != bitmap && bitmap.isRecycled() == false) {
  142. bitmap.recycle();
  143. }
  144. if (uri != null) {
  145. bitmap = BitmapFactory.decodeFile(uri.getPath(),
  146. options);
  147. }
  148. } catch (Exception e) {
  149. e.printStackTrace();
  150. }
  151. if (bitmap == null) {
  152. Bundle bundle = data.getExtras();
  153. if (bundle != null) {
  154. bitmap = (Bitmap) bundle.get("data");
  155. }
  156. }
  157. // 保存图片到本地
  158. if (bitmap != null) {
  159. new MyCamaralThread().start();
  160. } else {
  161. Toast.makeText(ImageCameraActivity.this, "照片获取失败", 1)
  162. .show();
  163. ImageCameraActivity.this.finish();
  164. }
  165. }
  166. }
  167. return;
  168. }
  169. ImageCameraActivity.this.finish();
  170. }
  171. class MyCamaralThread extends Thread {
  172. public void run() {
  173. // 压缩图片
  174. float mWeight = 480f;
  175. float mHight = 854f;
  176. float scaleWidth;
  177. float scaleHeight;
  178. scaleWidth = ((float) mWeight) / bitmap.getWidth();
  179. scaleHeight = ((float) mHight) / bitmap.getHeight();
  180. Matrix matrix = new Matrix();
  181. // matrix.postScale(scaleWidth, scaleHeight);
  182. matrix.postScale(0.3f, 0.3f);
  183. Bitmap mbit = null;
  184. mbit = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
  185. bitmap.getHeight(), matrix, true);
  186. ByteArrayOutputStream bStream = new ByteArrayOutputStream();
  187. mbit.compress(CompressFormat.PNG, 50, bStream);
  188. byte[] bytes = bStream.toByteArray();
  189. String data = Base64.encodeToString(bytes, Base64.DEFAULT);
  190. mIMGCallBack.callback(data);
  191. ImageCameraActivity.this.finish();
  192. }
  193. }
  194. public static void setIMGcallback(IMGCallBack myIMGCallBack) {
  195. mIMGCallBack = myIMGCallBack;
  196. }
  197. public interface IMGCallBack {
  198. public void callback(String data);
  199. }
  200. }

然后把Activity中接收到的data数据通过POST方式提交到服务器的接口上即可。


3、服务器端代码(服务器端为PHP)

  1. <?php
  2. $inputfile = $_POST['img'];//此处接受客户端POST过来的把图片加密转成String字符串过来的数据
  3. $file = fopen("./Valueimg/".$qimg , "w");//$qimg为同时POST提交过来的要保存的文件名,
  4. //文件保存下来之后,把路径保存在数据库中用来客户端需要时返回给客户端然后客户端再去加载上传过的图片
  5. $fwflag = fwrite( $file, base64_decode( $inputfile ) );
  6. fclose($file);
  7. printf("图片已经存入数据库");


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/530011
推荐阅读
相关标签
  

闽ICP备14008679号