Monday, November 17, 2008
C# .NET Image Manipulation Resize + Grayscale + TIFF
Code from the last three posts can be downloaded formatted properly here:
http://paulmaddox.net/BlogFiles/ImageManipulation_Program.cs.txt
Note you need to add the System.Drawing reference in order to get it to work with a new project.
http://paulmaddox.net/BlogFiles/ImageManipulation_Program.cs.txt
Note you need to add the System.Drawing reference in order to get it to work with a new project.
Convert C# .NET Bitmap to grayscale
Here's some code to convert a Bitmap into grayscale using luminance. Note, this does not change the color depth, rather it sets the pixels to grey within a 24bit color space.
private static Bitmap ToGrayscale(Bitmap bmIn)
{
Bitmap bmOut = new Bitmap(bmIn.Width, bmIn.Height, PixelFormat.Format24bppRgb);
for (int x = 0; x < bmIn.Width; x++)
{
for (int y = 0; y < bmIn.Height; y++)
{
Color px = bmIn.GetPixel(x, y);
int luminance = (int)((0.3f * px.R) + (0.59 * px.G) + (0.11 * px.B));
bmOut.SetPixel(x, y, Color.FromArgb(luminance, luminance, luminance));
}
}
return bmOut;
}
private static Bitmap ToGrayscale(Bitmap bmIn)
{
Bitmap bmOut = new Bitmap(bmIn.Width, bmIn.Height, PixelFormat.Format24bppRgb);
for (int x = 0; x < bmIn.Width; x++)
{
for (int y = 0; y < bmIn.Height; y++)
{
Color px = bmIn.GetPixel(x, y);
int luminance = (int)((0.3f * px.R) + (0.59 * px.G) + (0.11 * px.B));
bmOut.SetPixel(x, y, Color.FromArgb(luminance, luminance, luminance));
}
}
return bmOut;
}
C# .NET reading a bitmap, resizing / rescaling and saving as a TIFF
Here's some code to read in a bitmap and save a new bitmap at a quarter of the size. Note. a boilerplate method is needed to get the encoder for the write format. This makes it easy to change from TIFF to JPEG, PNG, etc.
// Load the bitmap from first argument filename
Bitmap bmIn = new Bitmap(inputFilename);
// Create a new bitmap from the first, scaling down as we go
Bitmap bmOut = new Bitmap(bmIn, new Size(bmIn.Width/2, bmIn.Height/2));
// Create an parameter set that we use to save the file
EncoderParameters encParams = new EncoderParameters(3);
// Set some parameters
encParams.Param[0] = new EncoderParameter(Encoder.ColorDepth, 24L);
encParams.Param[1] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone);
encParams.Param[2] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
// Save bitmap to second argument filename
bmOut2.Save(outputFilename, GetEncoder(ImageFormat.Tiff), encParams);
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
// Load the bitmap from first argument filename
Bitmap bmIn = new Bitmap(inputFilename);
// Create a new bitmap from the first, scaling down as we go
Bitmap bmOut = new Bitmap(bmIn, new Size(bmIn.Width/2, bmIn.Height/2));
// Create an parameter set that we use to save the file
EncoderParameters encParams = new EncoderParameters(3);
// Set some parameters
encParams.Param[0] = new EncoderParameter(Encoder.ColorDepth, 24L);
encParams.Param[1] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone);
encParams.Param[2] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
// Save bitmap to second argument filename
bmOut2.Save(outputFilename, GetEncoder(ImageFormat.Tiff), encParams);
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
Out of Memory / OutOfMemoryException on Graphics.FromImage with PixelFormat.Format16bppArgb1555 or PixelFormat.Format16bppGrayScale
If you have some code like this:
Bitmap bmp = new Bitmap(100,100, PixelFormat.Format16bppArgb1555);
Graphics gfx = Graphics.FromImage(bmp);
You will find you get an out of memory exception upon executing the code. The reason? .NET does not actually support Format16bppArgb1555 or PixelFormat.Format16bppGrayScale.
Bitmap bmp = new Bitmap(100,100, PixelFormat.Format16bppArgb1555);
Graphics gfx = Graphics.FromImage(bmp);
You will find you get an out of memory exception upon executing the code. The reason? .NET does not actually support Format16bppArgb1555 or PixelFormat.Format16bppGrayScale.
Wednesday, November 5, 2008
Visual Studio Errors
Thanks to Matt at Siemens for this one.
"If you get similar errors to below then deleting everything in the C:\Documents and Settings\\Local Settings\Application Data\Microsoft\VisualStudio\\ProjectAssemblies will solve this. Do not delete anything above this directory as you will lose all your toolbars and settings."
Error 4 The "ResolveAssemblyReference" task failed unexpectedly.
System.IO.IOException: Incorrect function.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, Boolean includeFiles, Boolean includeDirs, SearchOption searchOption)
at System.IO.Directory.GetDirectories(String path, String searchPattern, SearchOption searchOption)
at System.IO.Directory.GetDirectories(String path, String searchPattern)
at Microsoft.Build.Tasks.SystemState.GetDirectories(String path, String pattern)
at Microsoft.Build.Tasks.ReferenceTable.FindSatellites(Reference reference)
at Microsoft.Build.Tasks.ReferenceTable.FindAssociatedFiles()
at Microsoft.Build.Tasks.ReferenceTable.ComputeClosure()
at Microsoft.Build.Tasks.ReferenceTable.ComputeClosure(DependentAssembly[] remappedAssembliesValue, ITaskItem[] referenceAssemblyFiles, ITaskItem[] referenceAssemblyNames, ArrayList exceptions)
at Microsoft.Build.Tasks.ResolveAssemblyReference.Execute(FileExists fileExists, DirectoryExists directoryExists, GetDirectories getDirectories, GetAssemblyName getAssemblyName, GetAssemblyMetadata getAssemblyMetadata, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, GetLastWriteTime getLastWriteTime)
at Microsoft.Build.Tasks.ResolveAssemblyReference.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) MyProject
"If you get similar errors to below then deleting everything in the C:\Documents and Settings\
Error 4 The "ResolveAssemblyReference" task failed unexpectedly.
System.IO.IOException: Incorrect function.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, Boolean includeFiles, Boolean includeDirs, SearchOption searchOption)
at System.IO.Directory.GetDirectories(String path, String searchPattern, SearchOption searchOption)
at System.IO.Directory.GetDirectories(String path, String searchPattern)
at Microsoft.Build.Tasks.SystemState.GetDirectories(String path, String pattern)
at Microsoft.Build.Tasks.ReferenceTable.FindSatellites(Reference reference)
at Microsoft.Build.Tasks.ReferenceTable.FindAssociatedFiles()
at Microsoft.Build.Tasks.ReferenceTable.ComputeClosure()
at Microsoft.Build.Tasks.ReferenceTable.ComputeClosure(DependentAssembly[] remappedAssembliesValue, ITaskItem[] referenceAssemblyFiles, ITaskItem[] referenceAssemblyNames, ArrayList exceptions)
at Microsoft.Build.Tasks.ResolveAssemblyReference.Execute(FileExists fileExists, DirectoryExists directoryExists, GetDirectories getDirectories, GetAssemblyName getAssemblyName, GetAssemblyMetadata getAssemblyMetadata, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, GetLastWriteTime getLastWriteTime)
at Microsoft.Build.Tasks.ResolveAssemblyReference.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) MyProject
Subscribe to Posts [Atom]