图片转成base64编码
IOS:
// UIImage的图片转成Base64编码字符串: UIImage *originImage = [UIImage imageNamed:@"originImage.png"]; NSData *data = UIImageJPEGRepresentation(originImage, 1.0f); NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; // Base64编码字符串转UIImage的图片: NSData *decodedImageData = [[NSData alloc] initWithBase64EncodedString:encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters]; UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
android:
//将图片转换成base64编码 private void encode(String path) { //decode to bitmap Bitmap bitmap = BitmapFactory.decodeFile(path); Log.d(TAG, "bitmap width: " + bitmap.getWidth() + " height: " + bitmap.getHeight()); //convert to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] bytes = baos.toByteArray(); //base64 encode byte[] encode = Base64.encode(bytes,Base64.DEFAULT); String encodeString = new String(encode); mTvShow.setText(encodeString); } //将base64还原成图片 public void onDecodeClicked(View view) { byte[] decode = Base64.decode(mTvShow.getText().toString(),Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length); //save to image on sdcard saveBitmap(bitmap); } private void saveBitmap(Bitmap bitmap) { try { String path = Environment.getExternalStorageDirectory().getPath() +"/decodeImage.jpg"; Log.d("linc","path is "+path); OutputStream stream = new FileOutputStream(path); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream); stream.close(); Log.e("linc","jpg okay!"); } catch (IOException e) { e.printStackTrace(); Log.e("linc","failed: "+e.getMessage()); } }