1、原理
Android拍照将图片上传至服务器,其过程可以分为,1:将拍照的图片以64位的字节流形式存在;2:发布接收64位字节流并将字节流转换成图片的方法;3、访问发布的WebServer,实现图片的上传。
2、图片转为64位字节流
1、选择相机拍照和本地相册
调用相机拍照
paizhao.setOnClickListener(new paizhaoOnclick());
bendi.setOnClickListener(new bendiOnclick());
public class paizhaoOnclick implements View.OnClickListener{
@Override
public void onClick(View v) {
//Intent intent =new Intent("android.media.action.IMAGE_CAPTURE");
Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);
startActivityForResult(intent, 1000);
}
}
选择本地相册
public class bendiOnclick implements View.OnClickListener{
@Override
public void onClick(View v) {
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra("crop",true);
intent.putExtra("return-data",true);
startActivityForResult(intent,1001);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==1000&&resultCode==RESULT_OK){
String sdStatus= Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED))
{
return;
}
Bundle bundle=data.getExtras();
Bitmap bitmap=(Bitmap)bundle.get("data");
FileOutputStream b=null;
File file=new File("/sdcard/myImage/");
file.mkdirs();
String str=null;
Date date=null;
SimpleDateFormat format =new SimpleDateFormat("yyyyMMddHHmmss");
date=new Date();
str=format.format(date);
filename="/sdcard/myImage/"+str+".png";
try{
b=new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG,100,b);
}
catch(Exception e)
{
}
finally {
try
{
b.flush();
b.close();
}
catch(Exception e)
{
}
if(data!=null)
{
Bundle extras=data.getExtras();
Bitmap camerabitmap=(Bitmap)extras.get("data");
imageView.setImageBitmap(camerabitmap);
}
}
}
else if (requestCode==1001&&resultCode==RESULT_OK){
Uri uri= data.getData();
//获取游标
ContentResolver resolver =getContentResolver();
try {
Bitmap bitmap= BitmapFactory.decodeStream(resolver.openInputStream(uri));
imageView.setImageBitmap(bitmap);
}
catch (Exception e){
e.printStackTrace();
}
}
//将图片转为字节流
}
图片转为64位字节流的方法
public String picturezijie(String filename){
byte[]byte1=null;
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
try{
FileInputStream fileInputStream=new FileInputStream(filename);
byte[]buttfer=new byte[1024*10*1024];
int len=0;
while ((len=fileInputStream.read(buttfer))>=0)
{
byteArrayOutputStream.write(buttfer,0,len);
}
byte1=byteArrayOutputStream.toByteArray();
String imagebuffer= Base64.encodeToString(byte1,Base64.NO_WRAP);
byteArrayOutputStream.close();
fileInputStream.close();
return imagebuffer;
}
catch (Exception e)
{
return "";
}
}
3、服务器端接收
使用VS2013编写服务器接收64字节流文件并转换成图片存储的格式PNG、JPG等。
///
/// WebService1 的摘要说明
///
[WebService(Namespace = "http://***.***.***.**/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string UpImage(String dataURL,String path,String imgname)
{
//dataURL base64数据
//path 保存路径
//imgname图片名字
//string类型的相对路径
String filename = "";
//将,以前的多余字符串删除
String base64 = dataURL.Substring(dataURL.IndexOf(",")+1);
//定义一个Bitmap对象,接受转换完成的图片
System.Drawing.Bitmap bitmap = null;
try
{
//把纯净的Base64的资源给Inputstring
String inputString = base64;
//将Base64转换成等效的8位的无符号整形数组
byte[] arr = Convert.FromBase64String(inputString);
//转换成无法调整大小的MemoryStream对象
System.IO.MemoryStream ms = new System.IO.MemoryStream(arr);
//将MemoryStream对象转换成Bitmap对象
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);
//关闭资源
ms.Close();
bitmap = bmp;
//所要保存的相对路径及名字
filename = path + "/TJH_" + imgname + ".png";
//获取程序根目录
string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());
//转换成绝对路径
string imagesurl2 = tmpRootDir + filename.Replace(@"/", @"\");
//保存到服务器路径
bitmap.Save(imagesurl2, System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception) {
}
//返回相对路径
return filename;
}
}
4、将方法发布成WebServer
这里就不详细讲述WebServer发布的过程,大家可以参考发布
5、调用发布的服务
使用KSoap2调用上传照片的方法。
@Override
public void onClick(View v) {
String bytereturn=picturezijie(filename);
System.out.println("64位的字节流---------》》》》"+ bytereturn);
String filename1="486";
String path=null;
SoapObject request = new SoapObject(NAMESPACE, METHON_NAME);
request.addProperty("dataURL", bytereturn);
function(){ //外汇点差http://www.kaifx.cn/question/kaifx/1765.html
request.addProperty("path", path);
request.addProperty("imgname", filename1);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.bodyOut = request;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransportSE = new HttpTransportSE(URL);
httpTransportSE.debug = true;
try
{
httpTransportSE.call(SOAP_ACTION, envelope);
}
catch (Exception e)
{
e.printStackTrace();
}
SoapObject object = (SoapObject) envelope.bodyIn;
String result = object.getProperty(0).toString();
System.out.println("上传输出------------》》》"+result);
Toast.makeText(getApplicationContext(),"上传成功",Toast.LENGTH_SHORT).show();
}
}