Base64实现android端图片上传到server端

首先要下载Base64.java文件http://iharder.sourceforge.net/current/java/base64/

将代码复制到project中。

然后上代码:

android端代码:

private void setPicToView(Intent picdata) {
            Bundle extras = picdata.getExtras();
            if (extras != null) {
                 mBitmap = extras.getParcelable("data");
                view_images.setImageBitmap(mBitmap);
                
                LogUtil.i("运行reg", "运行了吗?");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                 //将bitmap一字节流输出 Bitmap.CompressFormat.PNG 压缩格式,100:压缩率。baos:字节流
                mBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byte[] buffer = baos.toByteArray();
                LogUtil.i("图片大小", buffer.length+"");
                //将图片的字节流数据加密成base64字符输出
                 photo = Base64.encodeBytes(buffer);
            }
        }

server端代码:

public static void SaveImages(String photo,String filePath){
        String imageName = new IPTimeStamp().getIPTimestamp()+".png";
        try {
            //对base64数据进行解码  生成字节数组。
            byte[] photoimg = new BASE64Decoder().decodeBuffer(photo);
            for(int i=0;i<photoimg.length;i++){
                if(photoimg[i]<0){
                    //调整异常数据
                    photoimg[i] += 256;
                }
            }
//            SysUtil.SysOut("图片的大小:" + photoimg.length);  
            File file = new File(filePath,imageName);  //创建一个目录 往里面写入图片
            if (!file.exists()) {  
                file.createNewFile();                    //file.mkdirs()创建一个目录,file.createNewFile()创建一个文件
            }  
            FileOutputStream out = new FileOutputStream(file);  
            out.write(photoimg);  
            out.flush();  
            out.close();  
        } catch (Exception e) {
            // TODO: handle exception
        }

原文地址:https://www.cnblogs.com/yxwkf/p/5070936.html