473,839 Members | 1,398 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 47960
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
17142
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 ----------------------- Posted by a user from .NET 247 (http://www.dotnet247.com/)
1
11512
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
5421
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 I can;t convert the image. I certainly don't want to upload it the the server filesystem, convert...
5
9657
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 recipient's email address or can download the text file as a zipped text file that will be presented to...
8
11662
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 size of 407 bytes and the total bytes array is 727. I am not sure what is wrong? your help would...
1
1476
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
2890
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, bitmap() as byte)
3
3970
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
4022
by: surajhs | last post by:
i need to convert image to binary data and create xml file in applet, Please send samples links
0
10795
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 a new concept, there is a concept called Steganography which enables to conceal your secret...
0
9855
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9697
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7828
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7017
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5682
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5866
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4064
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3133
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.