当前位置: 代码迷 >> Android >> android 用户头像,图片裁剪,上传并捎带用户数据base64code 方式
  详细解决方案

android 用户头像,图片裁剪,上传并捎带用户数据base64code 方式

热度:501   发布时间:2016-04-28 01:49:48.0
android 用户头像,图片裁剪,上传并附带用户数据base64code 方式

        图片上传的文件流我上一篇博客写了,这一篇我们说一下base64,base64上传方式就是将图片转换成base64码,然后把base64码以字符串的方式上传,然后服务器接收到以后再解码就可以了,相对于文件流来说比较简单;

           用户头像上传我们首先要获得图片的url然后再裁剪图片,然后把裁剪后的图片转换成base64然后在上传;

下边是安卓端代码:

首先我们要获得裁剪后的图片;一,选择图片;

代码如下,通过对话框选择获得图片的方式;

activity:

/*
* 提示对话框
*/
private void ShowPickDialog() {
new AlertDialog.Builder(this)
.setTitle("设置头像")
.setNegativeButton("相册", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 获取图片
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
startActivityForResult(intent, 1);
}
})
.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
// 调用拍照
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// 下面这句指定调用相机拍照后的照片存储的路径文件名用电话代替
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
.fromFile(new File(Environment
.getExternalStorageDirectory(),
userphone + ".jpg")));
startActivityForResult(intent, 2);
}
}).show();
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// 如果是直接从相册获取
case 1:
startPhotoZoom(data.getData());

break;
// 如果是调用相机拍照时
case 2:
File temp = new File(Environment.getExternalStorageDirectory()
+ "/" + userphone + ".jpg");
startPhotoZoom(Uri.fromFile(temp));
break;
// 取得裁剪后的图片
case 3:
/*
* 非空判断大家一定要验证,如果不验证的话,

*在剪裁之后如果发现不满意,要重新裁剪,丢弃  当前功能时,会报NullException,
*/
if (data != null) {
setPicToView(data);
}
break;
default:
break;


}
super.onActivityResult(requestCode, resultCode, data);
}


// 裁剪图片方法实现
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}


/*
* 保存裁剪之后的图片数据 
*/
private void setPicToView(Intent picdata) {
Bundle extras = picdata.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
Drawable drawable = new BitmapDrawable(photo);
// draw转换为String
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
byte[] b = stream.toByteArray(); 

// 将图片流以字符串形式存储下来
userimg = new String(Base64Coder.encodeLines(b));//在这里我们把图片转换成base64并存进userimg里面


zhuceimg.setImageDrawable(drawable);//图片显示在界面上zhuceimg为imageview控件
}
}

final Handler handlerzhuce = new Handler() {
public void handleMessage(Message msg) {


String str = (String) msg.obj;
if (str != null) {
Toast.makeText(Userzhuce.this, "完善信息成功!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(Userzhuce.this, "信息完善失败!!", Toast.LENGTH_SHORT)
.show();
}
}


};

//接下来是是数据的发送

public class OnClickListenerzhuce implements OnClickListener {
// 提交
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (zhucenc.getText().toString().equals("")) {
Toast.makeText(Userzhuce.this, "昵称不能为空!!!", Toast.LENGTH_SHORT)
.show();
} else {
new Thread(new Runnable() {
@Override
public void run() {//封装数据

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userphone",
userphone));
params.add(new BasicNameValuePair("username", zhucenc
.getText().toString()));
params.add(new BasicNameValuePair("address",
zhuceaddress.getText().toString()));
params.add(new BasicNameValuePair("photo",userimg));

FabuhttpClient zhuce = new FabuhttpClient();
try {
String str = zhuce.faburubbishifo(params,
HttpPath.USERUPDATE_PATH);
Message ms = handlerzhuce.obtainMessage();
ms.obj = str;
handlerzhuce.sendMessage(ms);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Toast.makeText(Userzhuce.this, "信息完善失败",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(Userzhuce.this, "完善信息失败!!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}).start();
}
}
}

下面是用到的两个类,一个是Base64Coder一个是FabuhttpClient;

FabuhttpClient代码如下:

public class FabuhttpClient {
    
public String faburubbishifo(List<NameValuePair> rubbishifo,String path) throws ClientProtocolException, IOException
{
String str=null;
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost(path);
try {
httppost.setEntity(new UrlEncodedFormEntity(rubbishifo,"UTF-8"));
HttpResponse httpResponse=httpclient.execute(httppost);

int code=httpResponse.getStatusLine().getStatusCode();
if(code==200)
{
str="发布成功";
Log.i("SMSpassActivity", "连接成功");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("client",str);
return str;
}
}

Base64Coder代码如下:

public class Base64Coder {// The line separator string of the operating system.
private static final String systemLineSeparator = System
.getProperty("line.separator");


// Mapping table from 6-bit nibbles to Base64 characters.
private static char[] map1 = new char[64];
static {
int i = 0;
for (char c = 'A'; c <= 'Z'; c++)
map1[i++] = c;
for (char c = 'a'; c <= 'z'; c++)
map1[i++] = c;
for (char c = '0'; c <= '9'; c++)
map1[i++] = c;
map1[i++] = '+';
map1[i++] = '/';
}


// Mapping table from Base64 characters to 6-bit nibbles.
private static byte[] map2 = new byte[128];
static {
for (int i = 0; i < map2.length; i++)
map2[i] = -1;
for (int i = 0; i < 64; i++)
map2[map1[i]] = (byte) i;
}

public static String encodeString(String s) {
return new String(encode(s.getBytes()));
}

public static String encodeLines(byte[] in) {
return encodeLines(in, 0, in.length, 76, systemLineSeparator);
}

public static String encodeLines(byte[] in, int iOff, int iLen,
int lineLen, String lineSeparator) {
int blockLen = (lineLen * 3) / 4;
if (blockLen <= 0)
throw new IllegalArgumentException();
int lines = (iLen + blockLen - 1) / blockLen;
int bufLen = ((iLen + 2) / 3) * 4 + lines * lineSeparator.length();
StringBuilder buf = new StringBuilder(bufLen);
int ip = 0;
while (ip < iLen) {
int l = Math.min(iLen - ip, blockLen);
buf.append(encode(in, iOff + ip, l));
buf.append(lineSeparator);
ip += l;
}
return buf.toString();
}

public static char[] encode(byte[] in) {
return encode(in, 0, in.length);
}

public static char[] encode(byte[] in, int iLen) {
return encode(in, 0, iLen);
}
public static char[] encode(byte[] in, int iOff, int iLen) {
int oDataLen = (iLen * 4 + 2) / 3; // output length without padding
int oLen = ((iLen + 2) / 3) * 4; // output length including padding
char[] out = new char[oLen];
int ip = iOff;
int iEnd = iOff + iLen;
int op = 0;
while (ip < iEnd) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iEnd ? in[ip++] & 0xff : 0;
int i2 = ip < iEnd ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '=';
op++;
out[op] = op < oDataLen ? map1[o3] : '=';
op++;
}
return out;
}
public static String decodeString(String s) {
return new String(decode(s));
}
public static byte[] decodeLines(String s) {
char[] buf = new char[s.length() + 3];
int p = 0;
for (int ip = 0; ip < s.length(); ip++) {
char c = s.charAt(ip);
if (c != ' ' && c != '\r' && c != '\n' && c != '\t')
buf[p++] = c;
}
while ((p % 4) != 0)
buf[p++] = '0';


return decode(buf, 0, p);
}
public static byte[] decode(String s) {
return decode(s.toCharArray());
}
public static byte[] decode(char[] in) {
return decode(in, 0, in.length);
}

public static byte[] decode(char[] in, int iOff, int iLen) {
if (iLen % 4 != 0)
throw new IllegalArgumentException(
"Length of Base64 encoded input string is not a multiple of 4.");
while (iLen > 0 && in[iOff + iLen - 1] == '=')
iLen--;
int oLen = (iLen * 3) / 4;
byte[] out = new byte[oLen];
int ip = iOff;
int iEnd = iOff + iLen;
int op = 0;
while (ip < iEnd) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iEnd ? in[ip++] : 'A';
int i3 = ip < iEnd ? in[ip++] : 'A';
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
throw new IllegalArgumentException(
"Illegal character in Base64 encoded data.");
int b0 = map2[i0];
int b1 = map2[i1];
int b2 = map2[i2];
int b3 = map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
throw new IllegalArgumentException(
"Illegal character in Base64 encoded data.");
int o0 = (b0 << 2) | (b1 >>> 4);
int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2);
int o2 = ((b2 & 3) << 6) | b3;
out[op++] = (byte) o0;
if (op < oLen)
out[op++] = (byte) o1;
if (op < oLen)
out[op++] = (byte) o2;
}
return out;
}


// Dummy constructor.
private Base64Coder() {
}

安卓端结束:下面是服务器端的代码:


public class UserUpdate extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);


}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean flag = false;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String userphone = request.getParameter("userphone");
String username = request.getParameter("username");
String address = request.getParameter("address");
//接收图片
String userimage = request.getParameter("photo");
System.out.println(userimage);
//base 转化图片
BASE64Decoder decoder = new BASE64Decoder();
byte[] ph = decoder.decodeBuffer(userimage);
System.out.println(ph);
for(int i=0;i<ph.length;++i)  
        {  
            if(ph[i]<0)  
            {//调整异常数据   
            ph[i]+=256;  
            }  
        }  
        //生成jpeg图片   
String imgFilePath =request.getSession().getServletContext()
.getRealPath("/")
+ "images"+"/"+userphone+".jpg";
//String imgFilePath ="d://223.jpg";// 新生成的图片
String userimg="http://192.168.1.110:8080/back/images"+"/"+userphone+".jpg";//用用户手机命名
System.out.println(userphone + username + address + "11111111111");
//更新信息
userservice se = new userserviceImp();

flag = se.updatauserapp(username,address, userimg,userphone);
if (flag) {
// 更新成功
OutputStream out = new FileOutputStream(imgFilePath);
out.write(ph);
out.flush();
out.close();
} else {
// 更新不成功
String set = "no";
PrintWriter out = response.getWriter();
out.print(set);
out.flush();
out.close();
}
}

服务器端结束;




}

  相关解决方案