base64示例

注意:base64 转码后存在+和/,经过http post发送前需要作url编码转换。有的语言http包默认没有提供url编码的功能。

PHP代码示例

<?php
//$file:图片地址
//Filetype: jpg,jpeg,png,bmp 
$file = "encode.jpg"; 
if($fp = fopen($file,"rb", 0)) 
{ 
    $gambar = fread($fp,filesize($file)); 
    fclose($fp); 

    $base64 = chunk_split(base64_encode($gambar)); 
    echo $base64; 
}     
?>

WEB代码示例

HTML
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
JS
function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    preview.src = reader.result;
    preview.src = reader.result;
        imgBase64Url = reader.result.replace(/^data:image\/(png|jpg|jpeg|bmp);base64,/, "");
        //doUpload(imgBase64Url) //此处可以自行接入图像接口
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}

GO代码示例

package main

import (
	"encoding/base64"
	"io/ioutil"
)

func main() {
	imageFile := "./test.jpg"
	image, _ := ioutil.ReadFile(imageFile)
	imageBase64 := base64.StdEncoding.EncodeToString(image)
}

PYTHON代码示例

import base64

with open('./test.jpg', 'rb') as bin_data:
	image_data = bin_data.read()
image_data_base64 = base64.b64encode(image_data)
print(image_data_base64)

 

Back to top