C Sharp PNG Greyscale Bitmap Score Matrix Code

From SnOwy - Ed's Wiki Notebook

Jump to: navigation, search

Might also need C_Sharp_PNG_Bitmap_Writing_with_System.Drawing ...

public static void SaveDoubleMatrixPNG(double[,] scoreMatrix, string FileName) {
        var rows = scoreMatrix.GetLength(0);
        var cols = scoreMatrix.GetLength(1);
        //var bitmap = new Bitmap(rows, cols);
        var bitmap = NewQuadBitmap(rows, cols);
        var graphics = Graphics.FromImage(bitmap);
        graphics.Clear(Color.White);
        var fileOut = new FileStream(FileName, FileMode.Create);
        var maxVal = Double.NegativeInfinity;
        var minVal = Double.PositiveInfinity;
        for(int i = 0; i < rows; i ++) {
            for(int j = 0; j < cols; j ++) {
                maxVal = scoreMatrix[i, j] > maxVal ? scoreMatrix[i, j] : maxVal;
                minVal = scoreMatrix[i, j] < minVal ? scoreMatrix[i, j] : minVal;
            }
        }
        var range = maxVal - minVal;
        for(int i = 0; i < rows; i ++) {
            for(int j = 0; j < cols; j ++) {
                int r = (int)((scoreMatrix[i,j] -minVal) /range *255);
                int g = (int)((scoreMatrix[i,j] -minVal) /range *255);
                int b = (int)((scoreMatrix[i,j] -minVal) /range *255);
                //notice that score matrix is row-major, but bitmap is x-major.
                //bitmap.SetPixel(j, i, Color.FromArgb(r, g, b));
                SetQuadPixelCell(bitmap, i, j, Color.FromArgb(r, g, b));
        }
    }
    bitmap.Save(fileOut, ImageFormat.Png);
    fileOut.Close();
}
public static Bitmap NewQuadBitmap(int rows, int cols) {
        return new Bitmap(rows * 2, cols * 2);
}
public static void SetQuadPixelCell(Bitmap bitmap, int row, int column, Color color) {
        bitmap.SetPixel(column *2,   row *2,   color);
        bitmap.SetPixel(column *2+1, row *2,   color);
        bitmap.SetPixel(column *2,   row *2+1, color);
        bitmap.SetPixel(column *2+1, row *2+1, color);
}
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox