android小文章——手机照片上传服务器方法

来源:互联网 发布:linux覆盖文件夹命令 编辑:程序博客网 时间:2024/04/29 03:08

话不多说,直接上代码

客户端代码:

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

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

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

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

Intent intent = new Intent(getApplicationContext(),ImageCameraActivity.class);startActivity(intent);Intent intent = new Intent(getApplicationContext(),ImagePhotoActivity.class);startActivity(intent);

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

import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import android.app.Activity;import android.content.ContentResolver;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.Bitmap.CompressFormat;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.media.ExifInterface;import android.net.Uri;import android.os.Bundle;import android.util.Base64;import android.view.Window;import android.widget.Toast;/** * 图库界面 * @author 苦涩 * 联系QQ:534429149 * */public class ImagePhotoActivity extends Activity {private Bitmap bm = null;private String Tag = "ImgAct";private Intent date = null;Uri uri = null;String sdStatus = null;boolean isstate = true;private static IMGCallBack1 mIMGCallBack;@Overrideprotected void onCreate(Bundle savedInstanceState) {requestWindowFeature(Window.FEATURE_NO_TITLE);super.onCreate(savedInstanceState);Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*");intent.putExtra("return-data", true);startActivityForResult(intent, 0);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);ContentResolver resolver = getContentResolver();if (requestCode == 0) {date = data;if (date != null) {Uri originalUri = data.getData(); // 获得图片的uriif (originalUri.getPath().toString() != null) {try {BitmapFactory.Options options = new BitmapFactory.Options();options.inSampleSize = 1;options.inPreferredConfig = Bitmap.Config.RGB_565;options.inPurgeable = true;options.inInputShareable = true;if (null != bm && bm.isRecycled() == false) {bm.recycle();}bm = BitmapFactory.decodeStream(resolver.openInputStream(Uri.parse(originalUri.toString())), null, options);} catch (Exception e) {e.printStackTrace();} // 显得到bitmap图片if (bm != null) {new MyCamaralThread().start();} else {Toast.makeText(ImagePhotoActivity.this, "图片获取失败", 1).show();}} else {Toast.makeText(ImagePhotoActivity.this, "图片获取失败", 1).show();}} else {ImagePhotoActivity.this.finish();}}}/****************** 解决图片旋转问题 ****************************/public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {// 旋转图片 动作Matrix matrix = new Matrix();;matrix.postRotate(angle);// 创建新的图片Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);return resizedBitmap;}/** * 读取图片属性:旋转的角度 *  * @param path *            图片绝对路径 * @return degree旋转的角度 */public static int readPictureDegree(String path) {int degree = 0;try {ExifInterface exifInterface = new ExifInterface(path);int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);switch (orientation) {case ExifInterface.ORIENTATION_ROTATE_90:degree = 90;break;case ExifInterface.ORIENTATION_ROTATE_180:degree = 180;break;case ExifInterface.ORIENTATION_ROTATE_270:degree = 270;break;}} catch (IOException e) {e.printStackTrace();}return degree;}/**********************************************/File fial = null;class MyCamaralThread extends Thread {public void run() {float mWeight = 480f;float mHight = 854f;float scaleWidth;float scaleHeight;scaleWidth = ((float) mWeight) / bm.getWidth();scaleHeight = ((float) mHight) / bm.getHeight();Matrix matrix = new Matrix();// matrix.postScale(scaleWidth, scaleHeight);matrix.postScale(0.3f, 0.3f);//压缩比例,不希望压缩的话就改成1,1Bitmap mbit = null;mbit = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(),matrix, true);ByteArrayOutputStream bStream = new ByteArrayOutputStream();mbit.compress(CompressFormat.PNG, 50, bStream);byte[] bytes = bStream.toByteArray();String data = Base64.encodeToString(bytes, Base64.DEFAULT);if (mIMGCallBack != null) {mIMGCallBack.callback(data);}ImagePhotoActivity.this.finish();}}public static void setIMGcallback(IMGCallBack1 myIMGCallBack) {mIMGCallBack = myIMGCallBack;}public interface IMGCallBack1 {public void callback(String data);}}


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

import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.Bitmap.CompressFormat;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.media.ExifInterface;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.provider.MediaStore;import android.util.Base64;import android.util.Log;import android.widget.Toast;/** * 拍照界面 * @author 苦涩 * 联系QQ:534429149 * */public class ImageCameraActivity extends Activity {private Bitmap bitmap;String imgPath = "/sdcard/img.jpg";Uri uri = null;String sdStatus = null;boolean isstate = true;private static IMGCallBack mIMGCallBack;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);sdStatus = Environment.getExternalStorageState();if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用Log.d("CameralAct","if (!sdStatus.equals(Environment.MEDIA_MOUNTED)");isstate = false;Intent it = new Intent("android.media.action.IMAGE_CAPTURE");startActivityForResult(it, Activity.DEFAULT_KEYS_DIALER);} else {Log.d("CameralAct","if (sdStatus.equals(Environment.MEDIA_MOUNTED)");isstate = true;File vFile = new File(imgPath);if (!vFile.exists()) {File vDirPath = vFile.getParentFile(); // new// File(vFile.getParent());vDirPath.mkdirs();}Uri uri = Uri.fromFile(vFile);Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//startActivityForResult(intent, 0);}}/****************** 解决图片旋转问题 ****************************/public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {// 旋转图片 动作Matrix matrix = new Matrix();;matrix.postRotate(angle);// 创建新的图片Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);return resizedBitmap;}/** * 读取图片属性:旋转的角度 *  * @param path *            图片绝对路径 * @return degree旋转的角度 */public static int readPictureDegree(String path) {int degree = 0;try {// 读取图片属性的ExifInterface exifInterface = new ExifInterface(path);int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);switch (orientation) {case ExifInterface.ORIENTATION_ROTATE_90:degree = 90;break;case ExifInterface.ORIENTATION_ROTATE_180:degree = 180;break;case ExifInterface.ORIENTATION_ROTATE_270:degree = 270;break;}} catch (IOException e) {e.printStackTrace();}return degree;}/**********************************************/File fial = null;@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (isstate && resultCode == Activity.RESULT_OK) {fial = new File(imgPath);uri = Uri.fromFile(fial);// 设置图片对应属性(压缩图片)BitmapFactory.Options options = new BitmapFactory.Options();options.inSampleSize = 2;options.inPreferredConfig = Bitmap.Config.RGB_565;options.inPurgeable = true;options.inInputShareable = true;int degree = readPictureDegree(fial.getAbsolutePath());if (null != bitmap && bitmap.isRecycled() == false) {bitmap.recycle();bitmap = null;}if (uri != null) {bitmap = BitmapFactory.decodeFile(uri.getPath(), options);bitmap = rotaingImageView(degree,BitmapFactory.decodeFile(uri.getPath(), options));}// 保存图片到本地if (bitmap != null) {new MyCamaralThread().start();} else {Toast.makeText(getApplicationContext(), "照片获取失败", 1).show();ImageCameraActivity.this.finish();}return;} else if (!isstate) {new MyCamaralThread().start();if (data != null) {Uri uri = data.getData();if (null != uri || uri.getPath() != null) {try {BitmapFactory.Options options = new BitmapFactory.Options();options.inSampleSize = 2;options.inPreferredConfig = Bitmap.Config.RGB_565;options.inPurgeable = true;options.inInputShareable = true;if (null != bitmap && bitmap.isRecycled() == false) {bitmap.recycle();}if (uri != null) {bitmap = BitmapFactory.decodeFile(uri.getPath(),options);}} catch (Exception e) {e.printStackTrace();}if (bitmap == null) {Bundle bundle = data.getExtras();if (bundle != null) {bitmap = (Bitmap) bundle.get("data");}}// 保存图片到本地if (bitmap != null) {new MyCamaralThread().start();} else {Toast.makeText(ImageCameraActivity.this, "照片获取失败", 1).show();ImageCameraActivity.this.finish();}}}return;}ImageCameraActivity.this.finish();}class MyCamaralThread extends Thread {public void run() {// 压缩图片float mWeight = 480f;float mHight = 854f;float scaleWidth;float scaleHeight;scaleWidth = ((float) mWeight) / bitmap.getWidth();scaleHeight = ((float) mHight) / bitmap.getHeight();Matrix matrix = new Matrix();// matrix.postScale(scaleWidth, scaleHeight);matrix.postScale(0.3f, 0.3f);Bitmap mbit = null;mbit = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, true);ByteArrayOutputStream bStream = new ByteArrayOutputStream();mbit.compress(CompressFormat.PNG, 50, bStream);byte[] bytes = bStream.toByteArray();String data = Base64.encodeToString(bytes, Base64.DEFAULT);mIMGCallBack.callback(data);ImageCameraActivity.this.finish();}}public static void setIMGcallback(IMGCallBack myIMGCallBack) {mIMGCallBack = myIMGCallBack;}public interface IMGCallBack {public void callback(String data);}}

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


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

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


0 0