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();

}

}

服务器端结束;

}

时间: 2024-07-30 01:31:50

android 用户头像,图片裁剪,上传并附带用户数据base64code 方式的相关文章

PHP+jQuery.photoClip.js支持手势的图片裁剪上传实例

PHP+jQuery.photoClip.js支持手势的图片裁剪上传实例,在手机上双指捏合为缩放,双指旋转可根据旋转方向每次旋转90度,在电脑上鼠标滚轮为缩放,双击则顺时针旋转90度. 下面让我们来看看核心代码: post的是base64,后端处理base64转存图片. 1 $("#clipArea").photoClip({ 2 width: 200, 3 height: 200, 4 file: "#file", 5 view: "#view"

vue中使用cropperjs进行图片裁剪上传

下面代码直接就可以复制使用了,但是需要在本地下个cropperjs,下载命令:npm install cropperjs --save-dev <template> <div id="yin"> <div id="demo"> <!-- 遮罩层 --> <div class="container" v-show="panel"> <div> <img

图片裁剪上传Jcrop

<link rel="stylesheet" href="../css/jquery.Jcrop.css"> <script src="../js/jquery.Jcrop.js"></script> 先是两个必不可少的东西 <style type="text/css"> /* Apply these styles only when #preview-pane has been

图片裁剪上传插件——jquery.photoClip.js

想要裁剪图片上传: 需要依赖的的插件为: [jquery.photoClip.js] 插件[iscroll-zoom.js] 插件[hammer.js] 插件 [lrz.all.bundle.js] 插件 [jquery-2.1.3.min.js] 在前端页面调取: <div id="clipArea"></div> <input type="file" id="file"> <button id=&qu

移动端图片裁剪上传—jQuery.cropper.js

jQuery.cropper.js是一款使用简单且功能强大的图片剪裁jQuery插件.该图片剪裁插件支持图片放大缩小,支持图片旋转,支持触摸屏设备,支持canvas,并且支持跨浏览器使用. 一.移动端获取本地相册兼容 安卓:<input type="file" accept="image/*" capture="camera" > ios:<input type="file" accept="ima

HTML5可预览多图片ajax上传(使用formData传递数据)

在介绍上传图片之前,我们简单的来了解下FormData的基本使用:介绍完成后这些基本知识后,我们会在文章最后提供一个demo,就是ajax多图片上传前预览效果. 1. formData的基本的用法:首先创建一个 空对象实例 代码如下:var formData = new FormData(); 1-1 获取值通过get(key)/getAll(key)来获取对应的value:比如: formData.get("name"); // 获取key为name的第一个值. formData.g

Android网页WebView图片文件上传的问题

在安卓下,webview上传图片点击是没用的,需要自己写一下. 网上关于这个的很多,基本都是抄来抄去,没什么用的. 这个日期比较新,而且能用 http://blog.csdn.net/djcken/article/details/46379929#comments 就是自定义实现 WebChromeClient 然后重写  openFileChooser  方法,获取 ValueCallback<Uri> valueCallback 当然,要注意不同版本的区别.,但5.0+的项目,就不能用了.

关于图片裁剪上传时同一张图片缓存问题的处理

做项目的时候,遇到了这样一个问题: 这个时候,我点击  “更换封面” ,跳出如下页面 此时,我还选择这个封面的原图,并进行裁切,如下图红色框里为我裁切后的头像 点击  “确定”  后,发现头像还是原来的头像,但是看接口里给的参数没错啊?!是裁切之后的图片啊?! 因为选择的是原来的图片,浏览器之前缓存了这个图片,这时再做修改也没有用. 解决办法是在图片后面加随机数: src: d.src.split("t")[0] + "?t=" + (new Date()).get

文件(图片)上传组件

1. 问题: https://zhuwenlong.com/blog/51f6519532ffd70b27000001 HTML5 File api 实现断点续传 http://www.jianshu.com/p/2a42a0c89640 html5 上传本地图片处理各种问题 2. 组件: http://fex.baidu.com/webuploader/ http://fex.baidu.com/webuploader/demo.html 百度上传组件 http://kindeditor.ne