C# 數組轉圖片


以下代碼是生成2048*4096的二維矩陣,然后遞增賦值,轉化成Bitmap圖片(科版存在本地)

又因為圖片控件不支持Bitmap賦值,再轉化為BitmapSource,

其中windows_middle是WPF中容器名稱

int img_width = 2048;
int img_height = 4096;
byte[] bytes = new byte[img_width * img_height];
int k = 0;
for (int i = 0; i < img_width; i++)
{
    for (int j = 0; j < img_height; j++)
    {
        bytes[k++] = (byte)(i + j);
    }
}
Bitmap bmp = ToGrayBitmap(bytes, img_width, img_height);

//bmp.Save(@"d:\test.png",System.Drawing.Imaging.ImageFormat.Png);
IntPtr ip = bmp.GetHbitmap();//從GDI+ Bitmap創建GDI位圖對象

BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());

System.Windows.Controls.Image image = new System.Windows.Controls.Image
{
    Width = img_width,
    Height = img_height,
    Name = "imgOutput",
    Source = bitmapSource
};
windows_middle.Children.Add(image);
public static Bitmap ToGrayBitmap(byte[] rawValues, int width, int height)
{
    //申請目標位圖的變量,並將其內存區域鎖定
    Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
    BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height),
    ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

    //獲取圖像參數
    int stride = bmpData.Stride;  // 掃描線的寬度  
    int offset = stride - width;  // 顯示寬度與掃描線寬度的間隙  
    IntPtr iptr = bmpData.Scan0;  // 獲取bmpData的內存起始位置  
    int scanBytes = stride * height;// 用stride寬度,表示這是內存區域的大小  

    //下面把原始的顯示大小字節數組轉換為內存中實際存放的字節數組
    int posScan = 0, posReal = 0;// 分別設置兩個位置指針,指向源數組和目標數組  
    byte[] pixelValues = new byte[scanBytes];  //為目標數組分配內存  

    for (int x = 0; x < height; x++)
    {
        //下面的循環節是模擬行掃描
        for (int y = 0; y < width; y++)
        {
            pixelValues[posScan++] = rawValues[posReal++];
        }
        posScan += offset;  //行掃描結束,要將目標位置指針移過那段“間隙”  
    }

    //用Marshal的Copy方法,將剛才得到的內存字節數組復制到BitmapData中
    System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, iptr, scanBytes);
    bmp.UnlockBits(bmpData);  // 解鎖內存區域  

    //下面的代碼是為了修改生成位圖的索引表,從偽彩修改為灰度
    ColorPalette tempPalette;
    using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
    {
        tempPalette = tempBmp.Palette;
    }
    for (int i = 0; i < 256; i++)
    {
        tempPalette.Entries[i] = Color.FromArgb(i, i, i);
    }

    bmp.Palette = tempPalette;

    //算法到此結束,返回結果
    return bmp;
}

效果如下:

 

 

 運行時間約100ms

也可以把ToGrayBitmap函數中的修改索引表的代碼注釋掉,得到的是偽彩色圖片

 

 

參考自:https://developer.51cto.com/art/200908/147763.htm

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM