I created a new class :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Images
{
class ImageTypeCheck
{
public static byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms, imageIn.RawFormat);
return ms.ToArray();
}
}
public enum ImageFormats
{
bmp,
jpeg,
gif,
tiff,
png,
unknown
}
public static ImageFormats GetImageFormat(byte[] bytes)
{
var bmp = Encoding.ASCII.GetBytes("BM"); // BMP
var gif = Encoding.ASCII.GetBytes("GIF"); // GIF
var png = new byte[] { 137, 80, 78, 71 }; // PNG
var tiff = new byte[] { 73, 73, 42 }; // TIFF
var tiff2 = new byte[] { 77, 77, 42 }; // TIFF
var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg
var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon
if (bmp.SequenceEqual(bytes.Take(bmp.Length)))
return ImageFormats.bmp;
if (gif.SequenceEqual(bytes.Take(gif.Length)))
return ImageFormats.gif;
if (png.SequenceEqual(bytes.Take(png.Length)))
return ImageFormats.png;
if (tiff.SequenceEqual(bytes.Take(tiff.Length)))
return ImageFormats.tiff;
if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))
return ImageFormats.tiff;
if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))
return ImageFormats.jpeg;
if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))
return ImageFormats.jpeg;
return ImageFormats.unknown;
}
}
}
Then in form1 when I loop over images I want to compare and check what type is each image :
foreach (string file in images)
{
using (var img = Image.FromFile(file))
{
var imgType = ImageTypeCheck.GetImageFormat(ImageTypeCheck.ImageToByteArray(img));
if (imgType != ImageFormat.Gif)
{
var destinationImagePath =
Path.ChangeExtension(@"d:\images\" + counter.ToString(), "gif");
img.Save(destinationImagePath, ImageFormat.Gif);
}
}
I'm getting error on the line :
if (imgType != ImageFormat.Gif)
Operator '!=' cannot be applied to operands of type 'ImageTypeCheck.ImageFormats' and 'ImageFormat'
imgType does not contains any formats from the class. I want to make that only if the image type is not real gif then convert it to gif.
Before I removed all the checking part to a new class it was all in form1 both the ImageToByteArray and the GetImageFormat and the enum. And only the GetImageFormat method was public static.
And then I used it like this without any errors :
foreach (string file in images)
{
using (var img = Image.FromFile(file))
{
var imgType = GetImageFormat(ImageToByteArray(img));
if (imgType != ImageFormat.gif)
{
var destinationImagePath =
Path.ChangeExtension(@"d:\images\" + counter.ToString(), "gif");
img.Save(destinationImagePath, System.Drawing.Imaging.ImageFormat.Gif);
}
}
but once I moved the two methods to the new class it's not working and give the error.