473,548 Members | 2,691 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert an Image to 8-bit grayscale

-How to convert any image(8,16,24,3 2 or 64-bit) to 8-bit grayscale

-i have tried to convert a 24-bit image to grayscale using setpixel
and getpixel functions, in vb.net
but i am unable to save that image in grayscale format.How do i do
that.It still saves in true color format.
-i used picturebox1.ima ge.save() method

-i tried to convert an 8-bit image into grayscale but was unable to
do it.

Nov 22 '06 #1
8 47858
Make a new memory bitmap with the pixel format set to grey scale. Then read
the coloured pixels one by one, average the red, green and blue value and
make that number the greyscale intensity and write it to the corresponding
pixel location of the memory bitmap. Then save the memory bitmap.
"pl************ @gmail.com" wrote:
-How to convert any image(8,16,24,3 2 or 64-bit) to 8-bit grayscale

-i have tried to convert a 24-bit image to grayscale using setpixel
and getpixel functions, in vb.net
but i am unable to save that image in grayscale format.How do i do
that.It still saves in true color format.
-i used picturebox1.ima ge.save() method

-i tried to convert an 8-bit image into grayscale but was unable to
do it.

Nov 22 '06 #2
well
can we set the pixel format to grayscale..for as i know framework
supports just the Format16bppGray scale..which also doesn't work
properly and my image is an 8-bit image
<--Help-->
Andrew McNab wrote:
Make a new memory bitmap with the pixel format set to grey scale. Then read
the coloured pixels one by one, average the red, green and blue value and
make that number the greyscale intensity and write it to the corresponding
pixel location of the memory bitmap. Then save the memory bitmap.
"pl************ @gmail.com" wrote:
-How to convert any image(8,16,24,3 2 or 64-bit) to 8-bit grayscale

-i have tried to convert a 24-bit image to grayscale using setpixel
and getpixel functions, in vb.net
but i am unable to save that image in grayscale format.How do i do
that.It still saves in true color format.
-i used picturebox1.ima ge.save() method

-i tried to convert an 8-bit image into grayscale but was unable to
do it.
Nov 23 '06 #3
hey,
I just found the following code in one of the other threads
Public Sub convert()
Dim g As Graphics
Dim ImageToConvert As Image = New Bitmap(m_Image)
Dim ImageAttributes As ImageAttributes = New ImageAttributes ()
Dim width As Integer = ImageToConvert. Width
Dim height As Integer = ImageToConvert. Height
Dim GrayShear()() As Single = New Single()() _
{New Single(4) {0.5, 0.5, 0.5, 0, 0}, _
New Single(4) {0.5, 0.5, 0.5, 0, 0}, _
New Single(4) {0.5, 0.5, 0.5, 0, 0}, _
New Single(4) {0, 0, 0, 1, 0}, _
New Single(4) {0, 0, 0, 0, 1}}
Dim colMatrix As ColorMatrix = New ColorMatrix(Gra yShear)
ImageAttributes .SetColorMatrix (colMatrix, ColorMatrixFlag .Default, _
ColorAdjustType .Bitmap)
g = Graphics.FromIm age(ImageToConv ert)
g.DrawImage(Ima geToConvert, _
New Rectangle(0, 0, width, height), 0, 0, _
width, height, GraphicsUnit.Pi xel, ImageAttributes )
m_Image = ImageToConvert
g.Dispose()
End Sub
'and it works

pl************@ gmail.com wrote:
well
can we set the pixel format to grayscale..for as i know framework
supports just the Format16bppGray scale..which also doesn't work
properly and my image is an 8-bit image
<--Help-->
Andrew McNab wrote:
Make a new memory bitmap with the pixel format set to grey scale. Then read
the coloured pixels one by one, average the red, green and blue value and
make that number the greyscale intensity and write it to the corresponding
pixel location of the memory bitmap. Then save the memory bitmap.
"pl************ @gmail.com" wrote:
-How to convert any image(8,16,24,3 2 or 64-bit) to 8-bit grayscale
>
-i have tried to convert a 24-bit image to grayscale using setpixel
and getpixel functions, in vb.net
but i am unable to save that image in grayscale format.How do i do
that.It still saves in true color format.
-i used picturebox1.ima ge.save() method
>
-i tried to convert an 8-bit image into grayscale but was unable to
do it.
>
>
Nov 23 '06 #4
<pl************ @gmail.comwrote in message
news:11******** **************@ e3g2000cwe.goog legroups.com...
hey,
I just found the following code in one of the other threads
Public Sub convert()
It's funny how this code keeps getting around. Makes one wonder when
Microsoft will just go ahead and put the damn functionality into .NET. It's
silly for it to not be built-in.

Of course, one might question why you are posting Visual Basic code to a C#
newsgroup, but I think we can all get the meaning of the code easily enough,
even if it's not the right language. :)

Anyway, when I had the same question, I used Google to find the answer.
Except that Google turned up a few variations, all based on the same code.
Only problem was that each variation had subtle problems with it.

At least the version you found has an array of the correct dimensions. All
of the versions I found actually had an array with the wrong number of
elements in some rows.

In any case, the one thing wrong with the version you just found is that it
doesn't actually map the colors in a perceptually correct way. A better
version of the array would be (still in VB, natch):
Dim GrayShear()() As Single = New Single()() _
{New Single(4) {0.3, 0.3, 0.3, 0, 0}, _
New Single(4) {0.59, 0.59, 0.59, 0, 0}, _
New Single(4) {0.11, 0.11, 0.11, 0, 0}, _
New Single(4) {0, 0, 0, 1, 0}, _
New Single(4) {0, 0, 0, 0, 1}}
Hope that helps...

Pete
Nov 23 '06 #5

hey,
thanks for the new matrix.It helped..
But i have a new issue now..m unable to save this image in grayscale
format..
when i check the file properties...us ing the follwing method

---------------------------------
Public Sub modInfo(ByVal infile As String)
Try
Dim oreg As RegistryKey
Dim ffile As New FileInfo(infile )
Dim instrm As New FileStream(infi le, FileMode.Open)
Dim img As Image = Image.FromStrea m(instrm)
Dim pos As Integer = 0

'file properties
intfilesize = CInt(ffile.Leng th)
strfullname = ffile.FullName
strtype = ffile.Extension .ToString
ffile = Nothing
oreg = Registry.Classe sRoot.OpenSubKe y(strtype)
If oreg Is Nothing Then
strtype = "UnKnown"
Else
strtype = oreg.GetValue(" ").ToString
oreg = Registry.Classe sRoot.OpenSubKe y(strtype)
strtype = oreg.GetValue(" ", "").ToStrin g
End If
oreg.Close()
'image properties
intwidth = CInt(img.Width)
intheight = CInt(img.Height )
strimgformat = img.PixelFormat .ToString
pos = strimgformat.La stIndexOf("p")
strimgformat = strimgformat.Su bstring(pos + 1)
strbitsperpixel = Image.GetPixelF ormatSize(img.P ixelFormat)
intHorRes = img.HorizontalR esolution
intVerRes = img.VerticalRes olution
instrm.Close()

Catch ex As Exception
MsgBox(ex.Messa ge)
End Try
End Sub
---------------------------------

, then the pixel format comes out to be 32 bit..non-grayscale...It just
doesn't seem to save correctly..The file generated when saved using the
bitmap's save method..doesn't even open in Photo editor..(It shows an
error)

--My question is how to save this grayscale file in 8 bits.

and i have a new question...
How do i convert a 24-bit image to 8-bit image (no grayscaling) and
vice-versa.....and save it as 24/8 bit..(should save correctly).

< --HELP-->
regards

Himani

Nov 24 '06 #6
and sorry for posting vb.net code to CSharp group i culdn't find the
dot net group..
and anyways i just need the logic
Thanks again

pl************@ gmail.com wrote:
hey,
thanks for the new matrix.It helped..
But i have a new issue now..m unable to save this image in grayscale
format..
when i check the file properties...us ing the follwing method

---------------------------------
Public Sub modInfo(ByVal infile As String)
Try
Dim oreg As RegistryKey
Dim ffile As New FileInfo(infile )
Dim instrm As New FileStream(infi le, FileMode.Open)
Dim img As Image = Image.FromStrea m(instrm)
Dim pos As Integer = 0

'file properties
intfilesize = CInt(ffile.Leng th)
strfullname = ffile.FullName
strtype = ffile.Extension .ToString
ffile = Nothing
oreg = Registry.Classe sRoot.OpenSubKe y(strtype)
If oreg Is Nothing Then
strtype = "UnKnown"
Else
strtype = oreg.GetValue(" ").ToString
oreg = Registry.Classe sRoot.OpenSubKe y(strtype)
strtype = oreg.GetValue(" ", "").ToStrin g
End If
oreg.Close()
'image properties
intwidth = CInt(img.Width)
intheight = CInt(img.Height )
strimgformat = img.PixelFormat .ToString
pos = strimgformat.La stIndexOf("p")
strimgformat = strimgformat.Su bstring(pos + 1)
strbitsperpixel = Image.GetPixelF ormatSize(img.P ixelFormat)
intHorRes = img.HorizontalR esolution
intVerRes = img.VerticalRes olution
instrm.Close()

Catch ex As Exception
MsgBox(ex.Messa ge)
End Try
End Sub
---------------------------------

, then the pixel format comes out to be 32 bit..non-grayscale...It just
doesn't seem to save correctly..The file generated when saved using the
bitmap's save method..doesn't even open in Photo editor..(It shows an
error)

--My question is how to save this grayscale file in 8 bits.

and i have a new question...
How do i convert a 24-bit image to 8-bit image (no grayscaling) and
vice-versa.....and save it as 24/8 bit..(should save correctly).

< --HELP-->
regards

Himani
Nov 24 '06 #7
<pl************ @gmail.comwrote in message
news:11******** *************@k 70g2000cwa.goog legroups.com...
[...]
, then the pixel format comes out to be 32 bit..non-grayscale...It just
doesn't seem to save correctly..The file generated when saved using the
bitmap's save method..doesn't even open in Photo editor..(It shows an
error)

--My question is how to save this grayscale file in 8 bits.

and i have a new question...
How do i convert a 24-bit image to 8-bit image (no grayscaling) and
vice-versa.....and save it as 24/8 bit..(should save correctly).
I don't know the answer to that one. My limited experience with the .NET
bitmap image support is that 8-bit and 16-bit images have little if no real
support. For sure, the "to grayscale" code here only converts colored
pixels to grayscale ones, but the image format remains the same. The image
is still a color format...it just doesn't have any non-grayscale pixels in
it after the conversion.

Whether that has anything to do with the problem you're having with saving
the file, I don't know. I haven't tried to use .NET to save out any image
bitmaps, so I'm not familiar with how well it works (or doesn't :) ).

For what it's worth, the bitmap image formats aren't very complicated. As
long as you didn't want compression, you should be able to write your own
file output code without too much trouble.

Pete
Nov 24 '06 #8
"Peter Duniho" <Np*********@Nn OwSlPiAnMk.comw rote:
><pl*********** *@gmail.comwrot e in message
>and i have a new question...
How do i convert a 24-bit image to 8-bit image (no grayscaling) and
vice-versa.....and save it as 24/8 bit..(should save correctly).
I don't know the answer to that one. My limited experience with the .NET
bitmap image support is that 8-bit and 16-bit images have little if no real
support.
I wrote some code to convert a bitmap into a monochrome image. The
code is in C#, but it uses interop to call the native win32 GDI
functions. (so, it's fast!). And it returns a geniune 1bit image,
rather than a 24bit one which happens to use only black and white..
http://www.wischik.com/lu/Programmer/1bpp

You can adapt this to do 8bpp. To do so, I downloaded the code and
modified it as follows:

static uint MAKERGB(int r,int g,int b)
{ return ((uint)(b&255)) | ((uint)((r&255) <<8)) |
((uint)((g&255) <<16));
}

unsafe public struct BITMAPINFO
{ public uint biSize;
public int biWidth, biHeight;
public short biPlanes, biBitCount;
public uint biCompression, biSizeImage;
public int biXPelsPerMeter , biYPelsPerMeter ;
public uint biClrUsed, biClrImportant;
public fixed uint cols[256];
}

bmi.biBitCount= 8; // ie. 1bpp
bmi.biClrUsed=2 56;
bmi.biClrImport ant=256;
// Now for the RGBQUAD table.
Random r = new Random();
for (int i=0; i<256; i++)
{ bmi.cols[i] = MAKERGB(r.Next( 256),r.Next(256 ),r.Next(128));
}
Note that this is now unsafe. It's unsafe because I embedded a fixed
array inside the BITMAPINFO structure, to store the palette. Can
anyone advise me what's a nice not-unsafe way to do this? Once I know,
I'll update the web page appropriately.

--
Lucian
Nov 24 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
17115
by: marcelo szwarc via .NET 247 | last post by:
I already broke my head, searched everywhere. PLEASE I NEED YOUR HELP! Do you know how can I convert an image file( like a gif or jpeg ) to a Base64 string? I need to use it to send embedded image files through email. I only need this to finish my app. Thank you!!! -------------------------------- From: marcelo szwarc ...
1
11470
by: Frank Nero | last post by:
I am trying to write an image to output stream, but can not figure out how to convert System.Web.UI.WebControls.Image to byte . Please give me some hint. Thanks,
1
5395
by: Daniel | last post by:
I have looked everywhere on the web for an answer to this and the only thing I can find is converting the image format when the file is present on the local filesystem. What I want to do is use a web form to upload a TIFF image (scanned images) and convert it to a JPEG before I insert it into SQL Server. The file upload part works great, but...
5
9608
by: Socrates | last post by:
I am interested in developing an online utility that will enable users to copy and past any image (or upload any image on the internet) to the online utility, which will then convert the image to text. The user may "convert image to text" and copy and paste the text displayed into any word document, or send the text displayed to the...
8
11638
by: piggy | last post by:
I am trying to convert an image to an byte array (tobytes() method) and from byte array back to an image (frombytes() method). The problem i have here is say the image size is 285 bytes but the total bytes is 635. I know it would include the header but the header should be the same size regardless of the image size. I tested the other image...
1
1461
by: gnkt4ujt2002 | last post by:
how to convert image into hex format in vs.net 2003 ....bcoz i hav 2 send image on mobile using sms tgate way.. i hav a clickatell sms gate way...
1
2877
by: =?Utf-8?B?UmljYXJkbyBGdXJ0YWRv?= | last post by:
I'm using OpenGL in Visual Basic .net 2005 and i need to use the following function glBitmap(width as integer,height as integer, xorig as single, yorig as single, xmove as single, ymove as single, bitmap as System.InPtr) or glBitmap(width as integer,height as integer, xorig as single, yorig as single, xmove as single, ymove as single,...
3
3935
by: surajhs | last post by:
hi, I am working on java applet, i created a interface to view image in panel on jlist selected image item which is in local machine path, Now i need to convert image to xml and along with i will open image viewer add some annotations save it in that xml file. Please help me with sample code or links. Thank you in advance
1
3994
by: surajhs | last post by:
i need to convert image to binary data and create xml file in applet, Please send samples links
0
10724
Debadatta Mishra
by: Debadatta Mishra | last post by:
Introduction In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information inside an image, hide your complete image as text ,search for a particular image inside a directory, minimize the size of the image. However this is not...
0
7444
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7711
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7954
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7467
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6039
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5367
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3478
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1054
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
755
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.