473,408 Members | 1,968 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Converting from Format24bppRgb to Format8bppIndexed distorts the image

I convert a bitmap from Format24bppRgb to Format8bppIndexed this way:

Expand|Select|Wrap|Line Numbers
  1. Bitmap bmp = new Bitmap("c:\\flower.bmp");
  2. BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
  3. Bitmap temp = new Bitmap(bmData.Width, bmData.Height, bmData.Stride, PixelFormat.Format8bppIndexed, bmData.Scan0);
  4. bmp.UnlockBits(bmData);
  5. pictureBox1.Image = temp; //But then the result is a destroyed image:
Would you please tell me where is the problem?
Attached Images
File Type: jpg flower.jpg (23.8 KB, 1058 views)
File Type: jpg f.jpg (43.6 KB, 1239 views)
Dec 26 '09 #1

✓ answered by tlhintoq

There is a lot more to converting an image than that.
Below is a "boiled down" sample that comes from another article.
http://www.codeproject.com/KB/graphi...lor_depth.aspx

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Drawing.Imaging;
  8. using System.Drawing.Printing;
  9. using System.Drawing.Drawing2D;
  10.  
  11. using System.IO;
  12. using System.Runtime.InteropServices;
  13. using System.Text;
  14. using System.Windows.Forms;
  15. using System.Drawing.Printing;
  16.  
  17. namespace FormPrinting
  18. {
  19.     public partial class Form1 : Form
  20.     {
  21.         private Font printFont;
  22.         private StreamReader streamToPrint;
  23.         private Image Orig;
  24.         private Image Converted;
  25.         private Hashtable m_knownColors = new Hashtable((int)Math.Pow(2, 20), 1.0f); 
  26.  
  27.         public Form1()
  28.         {
  29.             InitializeComponent();
  30.         }
  31.  
  32.  
  33.         private int GetPixelInfoSize(PixelFormat format)
  34.         {
  35.             switch (format)
  36.             {
  37.                 case PixelFormat.Format24bppRgb:
  38.                     {
  39.                         return 3;
  40.                     }
  41.                 default:
  42.                     {
  43.                         throw new ApplicationException("Only 24bit colors supported now");
  44.                     }
  45.             }
  46.  
  47.         }
  48.  
  49.  
  50.         // The PrintPage event is raised for each page to be printed.
  51.         private void pd_PrintPage(object sender, PrintPageEventArgs ev)
  52.         {
  53.  
  54.             ev.Graphics.PageScale = 25;// Print at 100% or 1:1 ratio 
  55.             //ev.PageSettings.PrinterSettings.
  56.             ev.Graphics.DrawImageUnscaled(System.Drawing.Image.FromFile(browseFile1.Text),0,0);
  57.             ev.HasMorePages = false;
  58.             return;
  59.             float linesPerPage = 0;
  60.             float yPos = 0;
  61.             int count = 0;
  62.             float leftMargin = ev.MarginBounds.Left;
  63.             float topMargin = ev.MarginBounds.Top;
  64.             string line = null;
  65.  
  66.             // Calculate the number of lines per page.
  67.             linesPerPage = ev.MarginBounds.Height /
  68.                printFont.GetHeight(ev.Graphics);
  69.  
  70.             // Print each line of the file.
  71.             while (count < linesPerPage &&
  72.                ((line = streamToPrint.ReadLine()) != null))
  73.             {
  74.                 yPos = topMargin + (count *
  75.                    printFont.GetHeight(ev.Graphics));
  76.                 ev.Graphics.DrawString(line, printFont, Brushes.Black,
  77.                    leftMargin, yPos, new StringFormat());
  78.                 count++;
  79.             }
  80.  
  81.             // If more lines exist, print another page.
  82.             if (line != null)
  83.                 ev.HasMorePages = true;
  84.             else
  85.                 ev.HasMorePages = false;
  86.         }
  87.  
  88.         private void browseFile1_PathChanged(object sender, Saint.Controls.BrowseFile.TextChangedEventArgs e)
  89.         {
  90.             Orig = Saint.GDI.Graphics.ImageFromFile(browseFile1.Text);
  91.             pbOrig.Image = Orig;
  92.             pbOrig.SizeMode = PictureBoxSizeMode.Zoom;
  93.             Converted = (Image) ConvertTo8bppFormat((Bitmap) Orig);
  94.             Converted = pbConverted.Image = Converted;
  95.             pbConverted.SizeMode = PictureBoxSizeMode.Zoom;
  96.         }
  97.  
  98.         private void btn8bppIndex_Click(object sender, EventArgs e)
  99.         {
  100.  
  101.         }
  102.         public Bitmap ConvertTo8bppFormat(Bitmap bmpSource)
  103.         {
  104.             int imageWidth = bmpSource.Width;
  105.             int imageHeight = bmpSource.Height;
  106.  
  107.             Bitmap bmpDest = null;
  108.             BitmapData bmpDataDest = null;
  109.             BitmapData bmpDataSource = null;
  110.  
  111.             try
  112.             {
  113.                 // Create new image with 8BPP format
  114.                 bmpDest = new Bitmap(
  115.                     imageWidth,
  116.                     imageHeight,
  117.                     PixelFormat.Format8bppIndexed
  118.                     );
  119.  
  120.                 // Lock bitmap in memory
  121.                 bmpDataDest = bmpDest.LockBits(
  122.                     new Rectangle(0, 0, imageWidth, imageHeight),
  123.                     ImageLockMode.ReadWrite,
  124.                     bmpDest.PixelFormat
  125.                     );
  126.  
  127.                 bmpDataSource = bmpSource.LockBits(
  128.                     new Rectangle(0, 0, imageWidth, imageHeight),
  129.                     ImageLockMode.ReadOnly,
  130.                     bmpSource.PixelFormat
  131.                 );
  132.  
  133.                 int pixelSize = GetPixelInfoSize(bmpDataSource.PixelFormat);
  134.                 byte[] buffer = new byte[imageWidth * imageHeight * pixelSize];
  135.                 byte[] destBuffer = new byte[imageWidth * imageHeight];
  136.  
  137.                 // Read all data to buffer
  138.                 ReadBmpData(bmpDataSource, buffer, pixelSize, imageWidth, imageHeight);
  139.  
  140.                 // Get color indexes
  141.                 MatchColors(buffer, destBuffer, pixelSize, bmpDest.Palette);
  142.  
  143.                 // Copy all colors to destination bitmaps
  144.                 WriteBmpData(bmpDataDest, destBuffer, imageWidth, imageHeight);
  145.  
  146.                 return bmpDest;
  147.             }
  148.             finally
  149.             {
  150.                 if (bmpDest != null) bmpDest.UnlockBits(bmpDataDest);
  151.                 if (bmpSource != null) bmpSource.UnlockBits(bmpDataSource);
  152.             }
  153.         }
  154.  
  155.         /// <summary>
  156.         /// Reads all bitmap data at once
  157.         /// </summary>
  158.         private void ReadBmpData(
  159.             BitmapData bmpDataSource,
  160.             byte[] buffer,
  161.             int pixelSize,
  162.             int width,
  163.             int height)
  164.         {
  165.             // Get unmanaged data start address
  166.             int addrStart = bmpDataSource.Scan0.ToInt32();
  167.  
  168.             for (int i = 0; i < height; i++)
  169.             {
  170.                 // Get address of next row
  171.                 IntPtr realByteAddr = new IntPtr(addrStart +
  172.                     System.Convert.ToInt32(i * bmpDataSource.Stride)
  173.                     );
  174.  
  175.                 // Perform copy from unmanaged memory
  176.                 // to managed buffer
  177.                 Marshal.Copy(
  178.                     realByteAddr,
  179.                     buffer,
  180.                     (int)(i * width * pixelSize),
  181.                     (int)(width * pixelSize)
  182.                 );
  183.             }
  184.         }
  185.  
  186.         /// <summary>
  187.         /// Writes bitmap data to unmanaged memory
  188.         /// </summary>
  189.         private void WriteBmpData(
  190.             BitmapData bmpDataDest,
  191.             byte[] destBuffer,
  192.             int imageWidth,
  193.             int imageHeight)
  194.         {
  195.             // Get unmanaged data start address
  196.             int addrStart = bmpDataDest.Scan0.ToInt32();
  197.  
  198.             for (int i = 0; i < imageHeight; i++)
  199.             {
  200.                 // Get address of next row
  201.                 IntPtr realByteAddr = new IntPtr(addrStart +
  202.                     System.Convert.ToInt32(i * bmpDataDest.Stride)
  203.                     );
  204.  
  205.                 // Perform copy from managed buffer
  206.                 // to unmanaged memory
  207.                 Marshal.Copy(
  208.                     destBuffer,
  209.                     i * imageWidth,
  210.                     realByteAddr,
  211.                     imageWidth
  212.                 );
  213.             }
  214.         }
  215.  
  216.         /// <summary>
  217.         /// This method matches indices from pallete ( 256 colors )
  218.         /// for each given 24bit color
  219.         /// </summary>
  220.         /// <param name="buffer">Buffer that contains color for each pixel</param>
  221.         /// <param name="destBuffer">Destination buffer that will contain index 
  222.         /// for each color</param>
  223.         /// <param name="pixelSize">Size of pixel info ( 24bit colors supported )</param>
  224.         /// <param name="pallete">Colors pallete ( 256 colors )</param>
  225.         private void MatchColors(
  226.             byte[] buffer,
  227.             byte[] destBuffer,
  228.             int pixelSize,
  229.             ColorPalette pallete)
  230.         {
  231.             int length = destBuffer.Length;
  232.  
  233.             // Temp storage for color info
  234.             byte[] temp = new byte[pixelSize];
  235.  
  236.             int palleteSize = pallete.Entries.Length;
  237.  
  238.             int mult_1 = 256;
  239.             int mult_2 = 256 * 256;
  240.  
  241.             int currentKey = 0;
  242.  
  243.             // For each color
  244.             for (int i = 0; i < length; i++)
  245.             {
  246.                 // Get next color
  247.                 Array.Copy(buffer, i * pixelSize, temp, 0, pixelSize);
  248.  
  249.                 // Build key for hash table
  250.                 currentKey = temp[0] + temp[1] * mult_1 + temp[2] * mult_2;
  251.  
  252.                 // If hash table already contains such color - fetch it
  253.                 // Otherwise perform calculation of similar color and save it to HT
  254.                 if (!m_knownColors.ContainsKey(currentKey))
  255.                 {
  256.                     destBuffer[i] = GetSimilarColor(pallete, temp, palleteSize);
  257.                     m_knownColors.Add(currentKey, destBuffer[i]);
  258.                 }
  259.                 else
  260.                 {
  261.                     destBuffer[i] = (byte)m_knownColors[currentKey];
  262.                 }
  263.             }// for
  264.         }
  265.  
  266.         /// <summary>
  267.         /// Returns Similar color
  268.         /// </summary>
  269.         /// <param name="palette"></param>
  270.         /// <param name="color"></param>
  271.         /// <returns></returns>
  272.         private byte GetSimilarColor(ColorPalette palette, byte[] color, int palleteSize)
  273.         {
  274.             byte minDiff = byte.MaxValue;
  275.             byte index = 0;
  276.  
  277.             if (color.Length == 3)// Implemented for 24bpp color
  278.             {
  279.                 // Loop all pallete ( 256 colors )
  280.                 for (int i = 0; i < palleteSize - 1; i++)
  281.                 {
  282.                     // Calculate similar color
  283.                     byte currentDiff = GetMaxDiff(color, palette.Entries[i]);
  284.  
  285.                     if (currentDiff < minDiff)
  286.                     {
  287.                         minDiff = currentDiff;
  288.                         index = (byte)i;
  289.                     }
  290.                 }// for
  291.             }
  292.             else// TODO implement it for other color types
  293.             {
  294.                 throw new ApplicationException("Only 24bit colors supported now");
  295.             }
  296.  
  297.             return index;
  298.         }
  299.  
  300.         /// <summary>
  301.         /// Return similar color
  302.         /// </summary>
  303.         /// <param name="a"></param>
  304.         /// <param name="b"></param>
  305.         /// <returns></returns>
  306.         private static byte GetMaxDiff(byte[] a, Color b)
  307.         {
  308.             // Get difference between components ( red green blue )
  309.             // of given color and appropriate components of pallete color
  310.             byte bDiff = a[0] > b.B ? (byte)(a[0] - b.B) : (byte)(b.B - a[0]);
  311.             byte gDiff = a[1] > b.G ? (byte)(a[1] - b.G) : (byte)(b.G - a[1]);
  312.             byte rDiff = a[2] > b.R ? (byte)(a[2] - b.R) : (byte)(b.R - a[2]);
  313.  
  314.             // Get max difference
  315.             byte max = bDiff > gDiff ? bDiff : gDiff;
  316.             max = max > rDiff ? max : rDiff;
  317.  
  318.             return max;
  319.         }
  320.     }
  321. }
  322.  

13 16656
tlhintoq
3,525 Expert 2GB
TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.
Dec 26 '09 #2
tlhintoq
3,525 Expert 2GB
There is a lot more to converting an image than that.
Below is a "boiled down" sample that comes from another article.
http://www.codeproject.com/KB/graphi...lor_depth.aspx

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Drawing.Imaging;
  8. using System.Drawing.Printing;
  9. using System.Drawing.Drawing2D;
  10.  
  11. using System.IO;
  12. using System.Runtime.InteropServices;
  13. using System.Text;
  14. using System.Windows.Forms;
  15. using System.Drawing.Printing;
  16.  
  17. namespace FormPrinting
  18. {
  19.     public partial class Form1 : Form
  20.     {
  21.         private Font printFont;
  22.         private StreamReader streamToPrint;
  23.         private Image Orig;
  24.         private Image Converted;
  25.         private Hashtable m_knownColors = new Hashtable((int)Math.Pow(2, 20), 1.0f); 
  26.  
  27.         public Form1()
  28.         {
  29.             InitializeComponent();
  30.         }
  31.  
  32.  
  33.         private int GetPixelInfoSize(PixelFormat format)
  34.         {
  35.             switch (format)
  36.             {
  37.                 case PixelFormat.Format24bppRgb:
  38.                     {
  39.                         return 3;
  40.                     }
  41.                 default:
  42.                     {
  43.                         throw new ApplicationException("Only 24bit colors supported now");
  44.                     }
  45.             }
  46.  
  47.         }
  48.  
  49.  
  50.         // The PrintPage event is raised for each page to be printed.
  51.         private void pd_PrintPage(object sender, PrintPageEventArgs ev)
  52.         {
  53.  
  54.             ev.Graphics.PageScale = 25;// Print at 100% or 1:1 ratio 
  55.             //ev.PageSettings.PrinterSettings.
  56.             ev.Graphics.DrawImageUnscaled(System.Drawing.Image.FromFile(browseFile1.Text),0,0);
  57.             ev.HasMorePages = false;
  58.             return;
  59.             float linesPerPage = 0;
  60.             float yPos = 0;
  61.             int count = 0;
  62.             float leftMargin = ev.MarginBounds.Left;
  63.             float topMargin = ev.MarginBounds.Top;
  64.             string line = null;
  65.  
  66.             // Calculate the number of lines per page.
  67.             linesPerPage = ev.MarginBounds.Height /
  68.                printFont.GetHeight(ev.Graphics);
  69.  
  70.             // Print each line of the file.
  71.             while (count < linesPerPage &&
  72.                ((line = streamToPrint.ReadLine()) != null))
  73.             {
  74.                 yPos = topMargin + (count *
  75.                    printFont.GetHeight(ev.Graphics));
  76.                 ev.Graphics.DrawString(line, printFont, Brushes.Black,
  77.                    leftMargin, yPos, new StringFormat());
  78.                 count++;
  79.             }
  80.  
  81.             // If more lines exist, print another page.
  82.             if (line != null)
  83.                 ev.HasMorePages = true;
  84.             else
  85.                 ev.HasMorePages = false;
  86.         }
  87.  
  88.         private void browseFile1_PathChanged(object sender, Saint.Controls.BrowseFile.TextChangedEventArgs e)
  89.         {
  90.             Orig = Saint.GDI.Graphics.ImageFromFile(browseFile1.Text);
  91.             pbOrig.Image = Orig;
  92.             pbOrig.SizeMode = PictureBoxSizeMode.Zoom;
  93.             Converted = (Image) ConvertTo8bppFormat((Bitmap) Orig);
  94.             Converted = pbConverted.Image = Converted;
  95.             pbConverted.SizeMode = PictureBoxSizeMode.Zoom;
  96.         }
  97.  
  98.         private void btn8bppIndex_Click(object sender, EventArgs e)
  99.         {
  100.  
  101.         }
  102.         public Bitmap ConvertTo8bppFormat(Bitmap bmpSource)
  103.         {
  104.             int imageWidth = bmpSource.Width;
  105.             int imageHeight = bmpSource.Height;
  106.  
  107.             Bitmap bmpDest = null;
  108.             BitmapData bmpDataDest = null;
  109.             BitmapData bmpDataSource = null;
  110.  
  111.             try
  112.             {
  113.                 // Create new image with 8BPP format
  114.                 bmpDest = new Bitmap(
  115.                     imageWidth,
  116.                     imageHeight,
  117.                     PixelFormat.Format8bppIndexed
  118.                     );
  119.  
  120.                 // Lock bitmap in memory
  121.                 bmpDataDest = bmpDest.LockBits(
  122.                     new Rectangle(0, 0, imageWidth, imageHeight),
  123.                     ImageLockMode.ReadWrite,
  124.                     bmpDest.PixelFormat
  125.                     );
  126.  
  127.                 bmpDataSource = bmpSource.LockBits(
  128.                     new Rectangle(0, 0, imageWidth, imageHeight),
  129.                     ImageLockMode.ReadOnly,
  130.                     bmpSource.PixelFormat
  131.                 );
  132.  
  133.                 int pixelSize = GetPixelInfoSize(bmpDataSource.PixelFormat);
  134.                 byte[] buffer = new byte[imageWidth * imageHeight * pixelSize];
  135.                 byte[] destBuffer = new byte[imageWidth * imageHeight];
  136.  
  137.                 // Read all data to buffer
  138.                 ReadBmpData(bmpDataSource, buffer, pixelSize, imageWidth, imageHeight);
  139.  
  140.                 // Get color indexes
  141.                 MatchColors(buffer, destBuffer, pixelSize, bmpDest.Palette);
  142.  
  143.                 // Copy all colors to destination bitmaps
  144.                 WriteBmpData(bmpDataDest, destBuffer, imageWidth, imageHeight);
  145.  
  146.                 return bmpDest;
  147.             }
  148.             finally
  149.             {
  150.                 if (bmpDest != null) bmpDest.UnlockBits(bmpDataDest);
  151.                 if (bmpSource != null) bmpSource.UnlockBits(bmpDataSource);
  152.             }
  153.         }
  154.  
  155.         /// <summary>
  156.         /// Reads all bitmap data at once
  157.         /// </summary>
  158.         private void ReadBmpData(
  159.             BitmapData bmpDataSource,
  160.             byte[] buffer,
  161.             int pixelSize,
  162.             int width,
  163.             int height)
  164.         {
  165.             // Get unmanaged data start address
  166.             int addrStart = bmpDataSource.Scan0.ToInt32();
  167.  
  168.             for (int i = 0; i < height; i++)
  169.             {
  170.                 // Get address of next row
  171.                 IntPtr realByteAddr = new IntPtr(addrStart +
  172.                     System.Convert.ToInt32(i * bmpDataSource.Stride)
  173.                     );
  174.  
  175.                 // Perform copy from unmanaged memory
  176.                 // to managed buffer
  177.                 Marshal.Copy(
  178.                     realByteAddr,
  179.                     buffer,
  180.                     (int)(i * width * pixelSize),
  181.                     (int)(width * pixelSize)
  182.                 );
  183.             }
  184.         }
  185.  
  186.         /// <summary>
  187.         /// Writes bitmap data to unmanaged memory
  188.         /// </summary>
  189.         private void WriteBmpData(
  190.             BitmapData bmpDataDest,
  191.             byte[] destBuffer,
  192.             int imageWidth,
  193.             int imageHeight)
  194.         {
  195.             // Get unmanaged data start address
  196.             int addrStart = bmpDataDest.Scan0.ToInt32();
  197.  
  198.             for (int i = 0; i < imageHeight; i++)
  199.             {
  200.                 // Get address of next row
  201.                 IntPtr realByteAddr = new IntPtr(addrStart +
  202.                     System.Convert.ToInt32(i * bmpDataDest.Stride)
  203.                     );
  204.  
  205.                 // Perform copy from managed buffer
  206.                 // to unmanaged memory
  207.                 Marshal.Copy(
  208.                     destBuffer,
  209.                     i * imageWidth,
  210.                     realByteAddr,
  211.                     imageWidth
  212.                 );
  213.             }
  214.         }
  215.  
  216.         /// <summary>
  217.         /// This method matches indices from pallete ( 256 colors )
  218.         /// for each given 24bit color
  219.         /// </summary>
  220.         /// <param name="buffer">Buffer that contains color for each pixel</param>
  221.         /// <param name="destBuffer">Destination buffer that will contain index 
  222.         /// for each color</param>
  223.         /// <param name="pixelSize">Size of pixel info ( 24bit colors supported )</param>
  224.         /// <param name="pallete">Colors pallete ( 256 colors )</param>
  225.         private void MatchColors(
  226.             byte[] buffer,
  227.             byte[] destBuffer,
  228.             int pixelSize,
  229.             ColorPalette pallete)
  230.         {
  231.             int length = destBuffer.Length;
  232.  
  233.             // Temp storage for color info
  234.             byte[] temp = new byte[pixelSize];
  235.  
  236.             int palleteSize = pallete.Entries.Length;
  237.  
  238.             int mult_1 = 256;
  239.             int mult_2 = 256 * 256;
  240.  
  241.             int currentKey = 0;
  242.  
  243.             // For each color
  244.             for (int i = 0; i < length; i++)
  245.             {
  246.                 // Get next color
  247.                 Array.Copy(buffer, i * pixelSize, temp, 0, pixelSize);
  248.  
  249.                 // Build key for hash table
  250.                 currentKey = temp[0] + temp[1] * mult_1 + temp[2] * mult_2;
  251.  
  252.                 // If hash table already contains such color - fetch it
  253.                 // Otherwise perform calculation of similar color and save it to HT
  254.                 if (!m_knownColors.ContainsKey(currentKey))
  255.                 {
  256.                     destBuffer[i] = GetSimilarColor(pallete, temp, palleteSize);
  257.                     m_knownColors.Add(currentKey, destBuffer[i]);
  258.                 }
  259.                 else
  260.                 {
  261.                     destBuffer[i] = (byte)m_knownColors[currentKey];
  262.                 }
  263.             }// for
  264.         }
  265.  
  266.         /// <summary>
  267.         /// Returns Similar color
  268.         /// </summary>
  269.         /// <param name="palette"></param>
  270.         /// <param name="color"></param>
  271.         /// <returns></returns>
  272.         private byte GetSimilarColor(ColorPalette palette, byte[] color, int palleteSize)
  273.         {
  274.             byte minDiff = byte.MaxValue;
  275.             byte index = 0;
  276.  
  277.             if (color.Length == 3)// Implemented for 24bpp color
  278.             {
  279.                 // Loop all pallete ( 256 colors )
  280.                 for (int i = 0; i < palleteSize - 1; i++)
  281.                 {
  282.                     // Calculate similar color
  283.                     byte currentDiff = GetMaxDiff(color, palette.Entries[i]);
  284.  
  285.                     if (currentDiff < minDiff)
  286.                     {
  287.                         minDiff = currentDiff;
  288.                         index = (byte)i;
  289.                     }
  290.                 }// for
  291.             }
  292.             else// TODO implement it for other color types
  293.             {
  294.                 throw new ApplicationException("Only 24bit colors supported now");
  295.             }
  296.  
  297.             return index;
  298.         }
  299.  
  300.         /// <summary>
  301.         /// Return similar color
  302.         /// </summary>
  303.         /// <param name="a"></param>
  304.         /// <param name="b"></param>
  305.         /// <returns></returns>
  306.         private static byte GetMaxDiff(byte[] a, Color b)
  307.         {
  308.             // Get difference between components ( red green blue )
  309.             // of given color and appropriate components of pallete color
  310.             byte bDiff = a[0] > b.B ? (byte)(a[0] - b.B) : (byte)(b.B - a[0]);
  311.             byte gDiff = a[1] > b.G ? (byte)(a[1] - b.G) : (byte)(b.G - a[1]);
  312.             byte rDiff = a[2] > b.R ? (byte)(a[2] - b.R) : (byte)(b.R - a[2]);
  313.  
  314.             // Get max difference
  315.             byte max = bDiff > gDiff ? bDiff : gDiff;
  316.             max = max > rDiff ? max : rDiff;
  317.  
  318.             return max;
  319.         }
  320.     }
  321. }
  322.  
Dec 26 '09 #3
Hello tlhintoq,
Thank you very much for your asnwer. I used the samlpe to convert from Format24bppRgb to Format8bppIndexed but yet the resulting image loses some color data. I feel the probmel is in MatchColors function, but I can not find it... I would be thankful if you could help me.
Dec 28 '09 #4
tlhintoq
3,525 Expert 2GB
I used the samlpe to convert from Format24bppRgb to Format8bppIndexed but yet the resulting image loses some color data.
Well... yeah. You went from 24 bits per pixel to 8. Of course it is going to loose some color data.

At 8 bits you have a pallet of 256 colors.
At 24 bits you have 16,777,216 colors.
Dec 28 '09 #5
Thank you very much! Actually I am going to write a program for color grading (or color gradient if I am not mistaken). I thought by converting the image to Format8bppIndexed, I would be able to change the colors by setting palette value instead of changing colors pixel by pixel. That is why I am looking for a way to do this conversion. I need a fast method for changing the color, contrast and resolution of images. Do you think the way I chose is a good one?
Dec 28 '09 #6
tlhintoq
3,525 Expert 2GB
I'm sorry. I don't really understand what your goal is. "A program for color grading / gradient" ??

You want to make a gradient? A smooth transition from Color A to Color B ?
Dec 29 '09 #7
I'm sorry that I could not explain. Yes, I mean smooth transition from one to color to another. For example to increase Red in an RGB image to make it more red. I did it by changing every pixel, but my teacher is not satisfied with it and says I have to do it by changing palettes as it takes shorter time.
Dec 29 '09 #8
tlhintoq
3,525 Expert 2GB
Bytes has a policy regarding assisting students with their homework.

The short version is that the volunteers here can't help you with schoolwork.
A) We don't know what material you have and have not learned in class.
B) We don't know the guidelines you must follow.
C) In the long run giving you the answers actually short changes your education.
Dec 29 '09 #9
It is not a school work. take it easy:) my research topic is much more complicated to be discussed here. This program is just a bit of work that I can ask everyone I want and what I have to do it something new that could not be found on the Internet:) So please help me to do this faster. I would appreciate it.
Dec 29 '09 #10
tlhintoq
3,525 Expert 2GB
It is not a school work.
but my teacher is not satisfied with it and says I have to do it by changing palettes as it takes shorter time.
Sounds like schoolwork to me. Maybe someone else will interpret that differently.
Dec 29 '09 #11
I am PhD student. My main work is with mathematic, not manipulating bitmaps.
Dec 29 '09 #12
ThatThatGuy
449 Expert 256MB
obviously .... convertting from a 24 bit bmp image to a 8 bit bitmap image...
will losea lot of colors....

notice the graphics of your windows XP machine.... when its newly formatted... and no graphic drivers are installed....

its 4 bit
Dec 29 '09 #13
thank you for your answer. I understand the reason of losing data. I am looking for a fast way for changing colors but not pixel by pixel. As Format24bppRgb format doesn't provide palette information, I thought it is good to convert it to another format which does have palette information. I need to have access to palettes but without losing data.
Dec 29 '09 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: iyuen | last post by:
I'm having problems with converting a byte array to an image object~ My byte array is an picture in VB6 StdPicture format. I've used propertybag to convert the picture into base64Array format in...
0
by: Mark Allen | last post by:
Hello, I am creating an RTF document server side for a report. However I am having problems converting images into the required RTF format. I am converting the image into a string (binary)...
0
by: Mil | last post by:
Hello, I'm trying to convert Images using Bitmap class. I want to use different options for example reduce the size of image. In my code I tried to create a Bitmap class instance with a...
3
by: Sharon | last post by:
I have a buffer of byte that contains a raw data of a 1 byte-per-pixel image data. I need to convert this buffer to a Bitmap of Format32bppArgb and to a Bitmap of Format24bppRgb. Can anybody...
4
by: Beginner | last post by:
How do I convert JPEG images to binary files in ASP.NET? Please advice. Thanks.
2
by: Laurent Navarro | last post by:
Hello, I am using a library which returns a byte containing RAW data, ie all pixels' color values coded in a byte array without header. I would like to save those data into a JPEG file so I...
3
by: Muddasir | last post by:
hi all i need to upload an image and if that image is coloured i need to convert it to black and white image ... till now i only uploaded images ... simple.. have no idea how to do this...
5
by: almurph | last post by:
RE: Tryign to convert Graphics object to a bitmap Hi, Hope you can help me with this. I have to open a file and add some text to it and then display it. So I create an Image object then...
3
by: srsaravanan | last post by:
i need coding for converting block and white image into RGB image
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.