2012-10-04

[C#] Image to Base64 後呈現

 

最近有一些圖片控管的需求跟跨 Server 傳遞問題

剛好看到 點部落上面有 有人發一篇文章   img base64 顯示圖片 支援 IE、Firefox、Chorme

想說就順便側一下..

案例概述

2012-10-04_152059

按下按鈕後 Server 會讀取一張根目錄下面 sample.jpg 的圖案 之後轉碼為 base64 且設定為 imageSample 的 src 屬性..

程式實作

將圖片轉 base64

C# Code:

/// <summary>
/// 自動判斷圖片格式
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static System.Drawing.Imaging.ImageFormat GetImageFormat(System.Drawing.Image img)
{
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
        return System.Drawing.Imaging.ImageFormat.Jpeg;
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
        return System.Drawing.Imaging.ImageFormat.Bmp;
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
        return System.Drawing.Imaging.ImageFormat.Png;
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Emf))
        return System.Drawing.Imaging.ImageFormat.Emf;
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Exif))
        return System.Drawing.Imaging.ImageFormat.Exif;
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
        return System.Drawing.Imaging.ImageFormat.Gif;
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon))
        return System.Drawing.Imaging.ImageFormat.Icon;
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp))
        return System.Drawing.Imaging.ImageFormat.MemoryBmp;
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
        return System.Drawing.Imaging.ImageFormat.Tiff;
    else
        return System.Drawing.Imaging.ImageFormat.Wmf;
}
 
/// <summary>
/// 將 Image 物件轉 Base64
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public string ImageToBase64(System.Drawing.Image image)
{
     
    MemoryStream ms = new MemoryStream();
 
    System.Drawing.Imaging.ImageFormat format = GetImageFormat(image);
 
    // 將圖片轉成 byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();
 
    // 將 byte[] 轉 base64
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
 
}


 



這裡面我是改寫   http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx



讓其自動判斷格式



之後我們呼叫這 function






 
protected void Button1_Click(object sender, EventArgs e)
{
 
// 讀取圖片並轉為 Image 物件
var image= System.Drawing.Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "sample.jpg");
 
// 設定至 imgSample 並且自動判定格式 
imgSample.Src = "data:image/" + GetImageFormat(image) + ";base64," + ImageToBase64(image);
 
// 將 base64 寫檔案 比較檔案大小
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory+"base64.txt",imgSample.Src);
}


結果



2012-10-04_152820



 



補充



看一下檔案大小



2012-10-04_152139



圖片 從 67KB-> 89 KB 這成長量不容小覷..



Sample: