C#將圖片和字撙節相互轉換並顯示到頁面上。本站提示廣大學習愛好者:(C#將圖片和字撙節相互轉換並顯示到頁面上)文章只能為提供參考,不一定能成為您想要的結果。以下是C#將圖片和字撙節相互轉換並顯示到頁面上正文
圖片轉換成字撙節先要轉換的IMage對象,轉換以後前往字撙節。字撙節轉換成圖片,要轉換的字撙節,轉換獲得的Image對象,依據圖片途徑前往圖片的字撙節,感興致的同伙看下上面的代碼。
C#將圖片和字撙節互相轉換代碼:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Drawing;
usingSystem.IO;
namespaceMicrosoft.Form.Base
{
classImageToByte
{
/// <summary>
/// 圖片轉換成字撙節
/// </summary>
/// <param name="img">要轉換的Image對象</param>
/// <returns>轉換後前往的字撙節</returns>
publicstaticbyte[] ImgToByt(Image img)
{
MemoryStream ms = newMemoryStream();
byte[] imagedata = null;
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imagedata = ms.GetBuffer();
returnimagedata;
}
/// <summary>
/// 字撙節轉換成圖片
/// </summary>
/// <param name="byt">要轉換的字撙節</param>
/// <returns>轉換獲得的Image對象</returns>
publicstaticImage BytToImg(byte[] byt)
{
MemoryStream ms = newMemoryStream(byt);
Image img = Image.FromStream(ms);
returnimg;
}
//
/// <summary>
/// 依據圖片途徑前往圖片的字撙節byte[]
/// </summary>
/// <param name="imagePath">圖片途徑</param>
/// <returns>前往的字撙節</returns>
privatestaticbyte[] getImageByte(stringimagePath)
{
FileStream files = newFileStream(imagePath, FileMode.Open);
byte[] imgByte = newbyte[files.Length];
files.Read(imgByte, 0, imgByte.Length);
files.Close();
returnimgByte;
}
}
}
將字撙節轉換為圖片文件顯示到頁面上
//Byte[] result;
System.IO.MemoryStream ms =new MemoryStream(result, 0, result.Length)
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
或許添加一個處置圖片的Handler,內容以下:
<%@ WebHandler Language="C#" Class="Handler" %>
using System.Web;
using System.IO;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
int CategoryID = int.Parse(context.Request.QueryString["CategoryID"]);
//挪用Categories.GetPicture獲得圖片stream
Stream stream = CategoriesPicture.GetPicture(CategoryID);
if (stream !=null) {
//獲得圖片stream年夜小
int buffersize = (int)stream.Length;
//樹立buffer
System.Byte[] buffer = new System.Byte[buffersize ] ;
//挪用stream.Read,從stream讀取到buffer,並前往count
int count = stream.Read(buffer, 0, buffersize);
//前往圖片字段buffer
if (count!=0)
context.Response.OutputStream.Write(buffer, 0, count);
}
}
public bool IsReusable {
get {
return false;
}
}
}
以上就是本文的全體內容,願望對年夜家進修C#將圖片和字撙節相互轉換並顯示到頁面上有所贊助。