图片转为String传个给服务端

来源:互联网 发布:linux 启动流程详解 编辑:程序博客网 时间:2024/04/29 04:19

上传头像等图片比较简单的一种就是直接把图片--- >String 再作为参数post给服务端

之所以用post是因为string都会很长~


下面见代码

try {ByteArrayOutputStream stream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 60, stream); byte[] b = stream.toByteArray(); // 将图片流以字符串形式存储下来 String tp = new String(Base64Coder.encodeLines(b));//tp 就是最终的参数} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}


为了检验本地可以尝试把string - 〉图片

                                byte[] tempb = Base64Coder.decode(tp);Bitmap bitmap = BitmapFactory.decodeByteArray(tempb, 0, tempb.length);ImageVIew.setImageBitmap(bitmap);


另外这个方法用到两个java类在下面

import java.io.IOException;import android.graphics.Bitmap;import android.graphics.BitmapFactory;public class Base64 {/** prevents anyone from instantiating this class */private Base64() {}/** * This character array provides the alphabet map from RFC1521. */private final static char ALPHABET[] = {// 0 1 2 3 4 5 6 7'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 2'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', // 3'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 4'o', 'p', 'q', 'r', 's', 't', 'u', 'v', // 5'w', 'x', 'y', 'z', '0', '1', '2', '3', // 6'4', '5', '6', '7', '8', '9', '+', '/' // 7};/** * Decodes a 7 bit Base64 character into its binary value. */private static int valueDecoding[] = new int[128];/** * initializes the value decoding array from the character map */static {for (int i = 0; i < valueDecoding.length; i++) {valueDecoding[i] = -1;}for (int i = 0; i < ALPHABET.length; i++) {valueDecoding[ALPHABET[i]] = i;}}/** * Converts a byte array into a Base64 encoded string. *  * @param data *            bytes to encode * @param offset *            which byte to start at * @param length *            how many bytes to encode; padding will be added if needed * @return base64 encoding of data; 4 chars for every 3 bytes */public static String encode(byte[] data, int offset, int length) {int i;int encodedLen;char[] encoded;// 4 chars for 3 bytes, run input up to a multiple of 3encodedLen = (length + 2) / 3 * 4;encoded = new char[encodedLen];for (i = 0, encodedLen = 0; encodedLen < encoded.length; i += 3, encodedLen += 4) {encodeQuantum(data, offset + i, length - i, encoded, encodedLen);}return new String(encoded);}/** * Encodes 1, 2, or 3 bytes of data as 4 Base64 chars. *  * @param in *            buffer of bytes to encode * @param inOffset *            where the first byte to encode is * @param len *            how many bytes to encode * @param out *            buffer to put the output in * @param outOffset *            where in the output buffer to put the chars */private static void encodeQuantum(byte in[], int inOffset, int len,char out[], int outOffset) {byte a = 0, b = 0, c = 0;a = in[inOffset];out[outOffset] = ALPHABET[(a >>> 2) & 0x3F];if (len > 2) {b = in[inOffset + 1];c = in[inOffset + 2];out[outOffset + 1] = ALPHABET[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];out[outOffset + 2] = ALPHABET[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)];out[outOffset + 3] = ALPHABET[c & 0x3F];} else if (len > 1) {b = in[inOffset + 1];out[outOffset + 1] = ALPHABET[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];out[outOffset + 2] = ALPHABET[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)];out[outOffset + 3] = '=';} else {out[outOffset + 1] = ALPHABET[((a << 4) & 0x30) + ((b >>> 4) & 0xf)];out[outOffset + 2] = '=';out[outOffset + 3] = '=';}}/** * Converts a Base64 encoded string to a byte array. *  * @param encoded *            Base64 encoded data * @return decode binary data; 3 bytes for every 4 chars - minus padding * @exception IOException *                is thrown, if an I/O error occurs reading the data */public static byte[] decode(String encoded) throws IOException {return decode(encoded, 0, encoded.length());}/** * Converts an embedded Base64 encoded string to a byte array. *  * @param encoded *            a String with Base64 data embedded in it * @param offset *            which char of the String to start at * @param length *            how many chars to decode; must be a multiple of 4 * @return decode binary data; 3 bytes for every 4 chars - minus padding * @exception IOException *                is thrown, if an I/O error occurs reading the data */public static byte[] decode(String encoded, int offset, int length)throws IOException {int i;int decodedLen;byte[] decoded;// the input must be a multiple of 4if (length % 4 != 0) {throw new IOException("Base64 string length is not multiple of 4");}// 4 chars for 3 bytes, but there may have been pad bytesdecodedLen = length / 4 * 3;if (encoded.charAt(offset + length - 1) == '=') {decodedLen--;if (encoded.charAt(offset + length - 2) == '=') {decodedLen--;}}decoded = new byte[decodedLen];for (i = 0, decodedLen = 0; i < length; i += 4, decodedLen += 3) {decodeQuantum(encoded.charAt(offset + i),encoded.charAt(offset + i + 1),encoded.charAt(offset + i + 2),encoded.charAt(offset + i + 3), decoded, decodedLen);}return decoded;}/** * Decode 4 Base64 chars as 1, 2, or 3 bytes of data. *  * @param in1 *            first char of quantum to decode * @param in2 *            second char of quantum to decode * @param in3 *            third char of quantum to decode * @param in4 *            forth char of quantum to decode * @param out *            buffer to put the output in * @param outOffset *            where in the output buffer to put the bytes */private static void decodeQuantum(char in1, char in2, char in3, char in4,byte[] out, int outOffset) throws IOException {int a = 0, b = 0, c = 0, d = 0;int pad = 0;a = valueDecoding[in1 & 127];b = valueDecoding[in2 & 127];if (in4 == '=') {pad++;if (in3 == '=') {pad++;} else {c = valueDecoding[in3 & 127];}} else {c = valueDecoding[in3 & 127];d = valueDecoding[in4 & 127];}if (a < 0 || b < 0 || c < 0 || d < 0) {throw new IOException("Invalid character in Base64 string");}// the first byte is the 6 bits of a and 2 bits of bout[outOffset] = (byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3));if (pad < 2) {// the second byte is 4 bits of b and 4 bits of cout[outOffset + 1] = (byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf));if (pad < 1) {// the third byte is 2 bits of c and 4 bits of dout[outOffset + 2] = (byte) (((c << 6) & 0xc0) | (d & 0x3f));}}}/** * 将字符串转换成Bitmap类型 *  * @param string * @return */public static Bitmap stringtoBitmap(String string) {Bitmap bitmap = null;try {byte[] bitmapArray;bitmapArray = decode(string);bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,bitmapArray.length);} catch (Exception e) {e.printStackTrace();}return bitmap;}}


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;}/** * Encodes a string into Base64 format. No blanks or line breaks are * inserted. *  * @param s *            A String to be encoded. * @return A String containing the Base64 encoded data. */public static String encodeString(String s) {return new String(encode(s.getBytes()));}/** * Encodes a byte array into Base 64 format and breaks the output into lines * of 76 characters. This method is compatible with * <code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>. *  * @param in *            An array containing the data bytes to be encoded. * @return A String containing the Base64 encoded data, broken into lines. */public static String encodeLines(byte[] in) {return encodeLines(in, 0, in.length, 76, systemLineSeparator);}/** * Encodes a byte array into Base 64 format and breaks the output into * lines. *  * @param in *            An array containing the data bytes to be encoded. * @param iOff *            Offset of the first byte in <code>in</code> to be processed. * @param iLen *            Number of bytes to be processed in <code>in</code>, starting *            at <code>iOff</code>. * @param lineLen *            Line length for the output data. Should be a multiple of 4. * @param lineSeparator *            The line separator to be used to separate the output lines. * @return A String containing the Base64 encoded data, broken into lines. */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();}/** * Encodes a byte array into Base64 format. No blanks or line breaks are * inserted in the output. *  * @param in *            An array containing the data bytes to be encoded. * @return A character array containing the Base64 encoded data. */public static char[] encode(byte[] in) {return encode(in, 0, in.length);}/** * Encodes a byte array into Base64 format. No blanks or line breaks are * inserted in the output. *  * @param in *            An array containing the data bytes to be encoded. * @param iLen *            Number of bytes to process in <code>in</code>. * @return A character array containing the Base64 encoded data. */public static char[] encode(byte[] in, int iLen) {return encode(in, 0, iLen);}/** * Encodes a byte array into Base64 format. No blanks or line breaks are * inserted in the output. *  * @param in *            An array containing the data bytes to be encoded. * @param iOff *            Offset of the first byte in <code>in</code> to be processed. * @param iLen *            Number of bytes to process in <code>in</code>, starting at *            <code>iOff</code>. * @return A character array containing the Base64 encoded data. */public static char[] encode(byte[] in, int iOff, int iLen) {int oDataLen = (iLen * 4 + 2) / 3; // output length without paddingint oLen = ((iLen + 2) / 3) * 4; // output length including paddingchar[] 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;}/** * Decodes a string from Base64 format. No blanks or line breaks are allowed * within the Base64 encoded input data. *  * @param s *            A Base64 String to be decoded. * @return A String containing the decoded data. * @throws IllegalArgumentException *             If the input is not valid Base64 encoded data. */public static String decodeString(String s) {return new String(decode(s));}/** * Decodes a byte array from Base64 format and ignores line separators, tabs * and blanks. CR, LF, Tab and Space characters are ignored in the input * data. This method is compatible with * <code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>. *  * @param s *            A Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException *             If the input is not valid Base64 encoded data. */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);}/** * Decodes a byte array from Base64 format. No blanks or line breaks are * allowed within the Base64 encoded input data. *  * @param s *            A Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException *             If the input is not valid Base64 encoded data. */public static byte[] decode(String s) {return decode(s.toCharArray());}/** * Decodes a byte array from Base64 format. No blanks or line breaks are * allowed within the Base64 encoded input data. *  * @param in *            A character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException *             If the input is not valid Base64 encoded data. */public static byte[] decode(char[] in) {return decode(in, 0, in.length);}/** * Decodes a byte array from Base64 format. No blanks or line breaks are * allowed within the Base64 encoded input data. *  * @param in *            A character array containing the Base64 encoded data. * @param iOff *            Offset of the first character in <code>in</code> to be *            processed. * @param iLen *            Number of characters to process in <code>in</code>, starting *            at <code>iOff</code>. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException *             If the input is not valid Base64 encoded data. */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() {}}



原创粉丝点击