using System;
using System.IO;
using System.Drawing;
using System.Configuration;
using System.Windows.Forms;
class ImageResizer
{
public static string _filePath = "";
public static System.Drawing.Image _image = null;
private const string MIME_JPEG = "image/jpeg";
private const string MIME_JPG = "image/jpeg";
private const string MIME_PJPEG = "image/pjpeg";
private const string MIME_GIF = "image/gif";
private const string MIME_BMP = "image/bmp";
private const string MIME_TIFF = "image/tiff";
private const string MIME_PNG = "image/x-png";
public string FilePath
{
get { return _filePath; }
}
public System.Drawing.Image Image
{
get { return _image; }
}
[STAThread]
public static void Main(string[] args)
{
args.ToString();
AppSettingsReader appSettings = new AppSettingsReader();
string InputPath = appSettings.GetValue("InputPath", typeof(string)).ToString();
string OutputPath = appSettings.GetValue("OutputPath", typeof(string)).ToString();
string thWidth = appSettings.GetValue("thWidth", typeof(string)).ToString();
string thQuality = appSettings.GetValue("thQuality", typeof(string)).ToString();
string strAction = appSettings.GetValue("strAction", typeof(string)).ToString(); //PREVIEW - PRINT
string PrintWidth = appSettings.GetValue("PrintWidth", typeof(string)).ToString();
string PrintHeight = appSettings.GetValue("PrintHeight", typeof(string)).ToString();
string OutputParameters = appSettings.GetValue("OutputParameters", typeof(string)).ToString();
string pathParameters = appSettings.GetValue("pathParameters", typeof(string)).ToString();
Bitmap NewBitmap1 = null;
Bitmap workingBitmap = null;
Bitmap destBitmap = null;
string sDPI = "";
string sHeight = "";
string sWidth = "";
//Para realizar pruebas de debug
string[] argsHC = new string[8];
argsHC[0] = InputPath;
argsHC[1] = OutputPath;
argsHC[2] = pathParameters;
argsHC[3] = thWidth;
argsHC[4] = thQuality;
argsHC[5] = strAction; //PREVIEW / PRINT / INFO
argsHC[6] = PrintWidth;
argsHC[7] = PrintHeight;
// args = argsHC;
try
{
//Requiered parameters
InputPath = args[0].ToString();
OutputPath = args[1].ToString();
//thWidth = args[2].ToString();
//thHeight = args[3].ToString();
//Optional parameters
try
{
pathParameters = args[2].ToString();
thWidth = args[3].ToString();
thQuality = args[4].ToString();
strAction = args[5].ToString();
PrintWidth = args[6].ToString();
PrintHeight = args[7].ToString();
}
catch
{
}
long lthQuality = Convert.ToInt64(thQuality);
try
{
if (strAction.ToUpper() == "INFO")
{
_filePath = InputPath;
_image = System.Drawing.Image.FromFile(InputPath);
//Creo un archivo para indicar los parámetros de la imágen
sDPI = _image.HorizontalResolution.ToString();
sHeight = _image.Height.ToString();
sWidth = _image.Width.ToString();
FileStream fsOut = new FileStream(pathParameters , FileMode.Append,
FileAccess.Write, FileShare.ReadWrite);
// Create a reader that can read characters from the FileStream.
StreamWriter sw = new StreamWriter(fsOut);
sw.WriteLine (sWidth + "," + sHeight + "," + sDPI);
sw.Flush();
sw.Close();
//Console.WriteLine(InputPath);
_image.Dispose();
}
}
catch
{
}
if (strAction.ToUpper() == "PREVIEW")
{
System.Drawing.Size MaxWidthSize = new Size(Convert.ToInt32(thWidth),Convert.ToInt32(thWidth)*5);
_filePath = InputPath;
_image = System.Drawing.Image.FromFile(InputPath);
System.Drawing.Size OriginalSize = new Size(_image.Width,_image.Height);
System.Drawing.Size NewSize = OriginalSize;
if (_image.Width > Convert.ToInt32(thWidth))
{
//System.Drawing.Size NewSize = scaleToFit(MaxWidthSize,OriginalSize);
NewSize = scaleToFit(MaxWidthSize,OriginalSize);
}
//int width1 = Convert.ToInt32(thWidth);
//int height1 = Convert.ToInt32(thHeight);
int width1 = NewSize.Width;
int height1 = NewSize.Height;
NewBitmap1 = new Bitmap(_image, width1, height1);
workingBitmap = NewBitmap1;
destBitmap = null;
//Create an in-memory stream which will be used to save
//the converted image
System.IO.Stream imgStream = new System.IO.MemoryStream();
string strFileType = DeriveFileType(InputPath);
string strFilePart = DeriveFileName(InputPath);
//strFileType
System.Drawing.Imaging.ImageFormat imgFormat = null;
imgFormat = ImageFormatFromMimeType("MIME_" + strFileType.ToUpper());
//ImageCodecInfo destCodec = FindCodecForType(Clipping.ClippingDotNet.MimeTypeFromImageFormat(ImageFormat.Jpeg));
System.Drawing.Imaging.ImageCodecInfo destCodec = FindCodecForType(MimeTypeFromImageFormat(imgFormat));
if (destCodec == null)
{
//No codec available for that format
throw new ArgumentException("The requested format " +
MimeTypeFromImageFormat(System.Drawing.Imaging.ImageFormat.Jpeg) +
" does not have an available codec installed",
"destFormat");
}
// Set the quality to 100% (must be a long)
System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameter qualityParam = new System.Drawing.Imaging.EncoderParameter(qualityEncoder, lthQuality);//80L);
//Create an EncoderParameters collection to contain the
//parameters that control the dest format's encoder
System.Drawing.Imaging.EncoderParameters destEncParams = new System.Drawing.Imaging.EncoderParameters(1);
//Use quality parameter
//EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, "90");
destEncParams.Param[0] = qualityParam;
workingBitmap.Save(imgStream,destCodec,destEncParams);
//At this point, imgStream contains the binary form of the
//bitmap in the target format. All that remains is to load it
//into a new bitmap object
destBitmap = new Bitmap(imgStream);
destBitmap.Save(OutputPath);
}
if (strAction.ToUpper() == "PRINT")
{
System.Drawing.Size MaxWidthSize = new Size(Convert.ToInt32(PrintWidth),Convert.ToInt32(PrintHeight));
//PrintWidth - PrintHeight
_filePath = InputPath;
_image = System.Drawing.Image.FromFile(InputPath);
System.Drawing.Size OriginalSize = new Size(_image.Width,_image.Height);
System.Drawing.Size NewSize = OriginalSize;
if (OriginalSize.Width > Convert.ToInt32(PrintWidth) || OriginalSize.Height > Convert.ToInt32(PrintHeight))
{
//System.Drawing.Size NewSize = scaleToFit(MaxWidthSize,OriginalSize);
NewSize = scaleToFit(MaxWidthSize,OriginalSize);
}
//int width1 = Convert.ToInt32(thWidth);
//int height1 = Convert.ToInt32(thHeight);
int width1 = NewSize.Width;
int height1 = NewSize.Height;
NewBitmap1 = new Bitmap(_image, width1, height1);
workingBitmap = NewBitmap1;
destBitmap = null;
//Create an in-memory stream which will be used to save
//the converted image
System.IO.Stream imgStream = new System.IO.MemoryStream();
string strFileType = DeriveFileType(InputPath);
string strFilePart = DeriveFileName(InputPath);
//strFileType
System.Drawing.Imaging.ImageFormat imgFormat = null;
imgFormat = ImageFormatFromMimeType("MIME_" + strFileType.ToUpper());
//ImageCodecInfo destCodec = FindCodecForType(Clipping.ClippingDotNet.MimeTypeFromImageFormat(ImageFormat.Jpeg));
System.Drawing.Imaging.ImageCodecInfo destCodec = FindCodecForType(MimeTypeFromImageFormat(imgFormat));
if (destCodec == null)
{
//No codec available for that format
throw new ArgumentException("The requested format " +
MimeTypeFromImageFormat(System.Drawing.Imaging.ImageFormat.Jpeg) +
" does not have an available codec installed",
"destFormat");
}
// Set the quality to 100% (must be a long)
System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameter qualityParam = new System.Drawing.Imaging.EncoderParameter(qualityEncoder, lthQuality);//80L);
//Create an EncoderParameters collection to contain the
//parameters that control the dest format's encoder
System.Drawing.Imaging.EncoderParameters destEncParams = new System.Drawing.Imaging.EncoderParameters(1);
//Use quality parameter
//EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, "90");
destEncParams.Param[0] = qualityParam;
workingBitmap.Save(imgStream,destCodec,destEncParams);
//At this point, imgStream contains the binary form of the
//bitmap in the target format. All that remains is to load it
//into a new bitmap object
destBitmap = new Bitmap(imgStream);
destBitmap.Save(OutputPath);
}
/*
//Creo un archivo para indicar cuantos slides hay
FileStream fsOut = new FileStream(OutputPath + "\\TotalSlides.txt" , FileMode.Append,
FileAccess.Write, FileShare.ReadWrite);
// Create a reader that can read characters from the FileStream.
StreamWriter sw = new StreamWriter(fsOut);
sw.WriteLine (files.Length.ToString());
sw.Flush();
sw.Close();
*/
}
catch (Exception ex)
{
Console.WriteLine("Image Resizer V1.95 INFO");
Console.WriteLine("Copyright 2008");
Console.WriteLine("usage: ImageResizer [Parameters]");
Console.WriteLine("Parameter 1: complete INPUT path to the image file (*)");
Console.WriteLine("Parameter 2: complete OUTPUT path to resized file (*)");
Console.WriteLine("Parameter 3: complete PATH to save TXT with parameters");
Console.WriteLine("Parameter 4: maximum width for the thumbnail JPG(default = 600)");
Console.WriteLine("Parameter 5: Quality of JPG (default = 100)");
Console.WriteLine("Parameter 6: Action (default = PRINT)");
Console.WriteLine("Parameter 7: maximum width for the PRINT image (default = 638)");
Console.WriteLine("Parameter 8: maximum height for the PRINT image (default = 750)");
Console.WriteLine("");
Console.WriteLine("Parameters marked with (*) are required.");
//Console.WriteLine(ex.InnerException.ToString());
//Creo un archivo para indicar cuantos slides hay
FileStream fsOut = new FileStream(Application.StartupPath.ToString() + "\\ERROR_RESIZER.txt" , FileMode.Append,
FileAccess.Write, FileShare.ReadWrite);
// Create a reader that can read characters from the FileStream.
StreamWriter sw = new StreamWriter(fsOut);
sw.WriteLine (ex.Message.ToString());
sw.Flush();
sw.Close();
}
/*
try
{
if (OutputParameters.ToUpper() == "YES")
{
//InputPath
//System.Drawing.Graphics pete = Graphics.FromImage(_image);
//Creo un archivo para indicar los parámetros de la imágen
sDPI = _image.HorizontalResolution.ToString();
sHeight = _image.Height.ToString();
sWidth = _image.Width.ToString();
// Console.WriteLine(sWidth + "," + sHeight + "," + sDPI);
// Console.WriteLine(pathParameters);
//InputPath = InputPath.ToUpper().Replace("JPG","TXT");
//InputPath = InputPath.ToUpper().Replace("GIF","TXT");
FileStream fsOut = new FileStream(pathParameters , FileMode.Append,
FileAccess.Write, FileShare.ReadWrite);
// Create a reader that can read characters from the FileStream.
StreamWriter sw = new StreamWriter(fsOut);
sw.WriteLine (sWidth + "," + sHeight + "," + sDPI);
sw.Flush();
sw.Close();
//Console.WriteLine(InputPath);
}
_image.Dispose();
NewBitmap1.Dispose();
workingBitmap.Dispose();
destBitmap.Dispose();
}
catch
{
}
*/
}
///
/// This method takes a file name or path and attempts to extract the file extension from it.
///
/// A full file name or path.
/// string
public static string DeriveFileType(string fileName)
{
string fileType = "";
string[] fileParts;
if (fileName.IndexOf(System.IO.Path.DirectorySeparatorChar) != -1)
{
string[] filePieces = fileName.Split(System.IO.Path.DirectorySeparatorChar);
fileParts = filePieces[filePieces.Length - 1].Split('.');
}
else
{
fileParts = fileName.Split('.');
}
fileType = fileParts[fileParts.Length - 1];
if (fileType == "")
{
throw new Exception("Invalid file name passed to DeriveFileType().");
}
else
{
return fileType;
}
}
///
/// This method takes a file name or path and attempts to extract the file extension from it.
///
/// A full file name or path.
/// string
public static string DeriveFileName(string fileName)
{
string finalName = "";
string[] fileParts;
if (fileName.IndexOf(System.IO.Path.DirectorySeparatorChar) != -1)
{
string[] filePieces = fileName.Split(System.IO.Path.DirectorySeparatorChar);
fileParts = filePieces[filePieces.Length - 1].Split('.');
}
else
{
fileParts = fileName.Split('.');
}
finalName = fileParts[fileParts.Length - 2];
if (finalName == "")
{
throw new Exception("Invalid file name passed to DeriveFileName().");
}
else
{
return finalName;
}
}
///
/// Gets the encoder information for the specified mimetype. Used in imagescaling
///
/// The mimetype of the picture.
/// System.Drawing.Imaging.ImageCodecInfo
public static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(string mimeType)
{
System.Drawing.Imaging.ImageCodecInfo [] myEncoders =
System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
foreach (System.Drawing.Imaging.ImageCodecInfo myEncoder in myEncoders)
if (myEncoder.MimeType == mimeType)
return myEncoder;
return null;
}
public static System.Drawing.Imaging.ImageFormat ImageFormatFromMimeType(string mimeType)
{
switch (mimeType)
{
case "MIME_JPG":
return System.Drawing.Imaging.ImageFormat.Jpeg;
case "MIME_JPEG":
return System.Drawing.Imaging.ImageFormat.Jpeg;
case "MIME_PJPEG":
return System.Drawing.Imaging.ImageFormat.Jpeg;
case "MIME_GIF":
return System.Drawing.Imaging.ImageFormat.Gif;
case "MIME_BMP":
return System.Drawing.Imaging.ImageFormat.Bmp;
case "MIME_TIFF":
return System.Drawing.Imaging.ImageFormat.Tiff;
case "MIME_PNG":
return System.Drawing.Imaging.ImageFormat.Png;
default:
throw new ArgumentException("Unsupported MIME type '" + mimeType + "'", "mimeType");
}
}
public static string MimeTypeFromImageFormat(System.Drawing.Imaging.ImageFormat format)
{
if (format.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
{
return MIME_JPEG;
}
else if (format.Equals(System.Drawing.Imaging.ImageFormat.Gif))
{
return MIME_GIF;
}
else if (format.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
{
return MIME_BMP;
}
else if (format.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
{
return MIME_TIFF;
}
else if (format.Equals(System.Drawing.Imaging.ImageFormat.Png))
{
return MIME_PNG;
}
else
{
throw new ArgumentException("Unsupported image format '" + format + "'", "format");
}
}
public static System.Drawing.Imaging.ImageCodecInfo FindCodecForType(string mimeType)
{
System.Drawing.Imaging.ImageCodecInfo[] imgEncoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
for (int i = 0; i < imgEncoders.GetLength(0); i++)
{
if (imgEncoders[i].MimeType == mimeType)
{
//Found it
return imgEncoders[i];
}
}
//No encoders match
return null;
}
private static Size scaleToFit(Size target, Size original)
{
if (target.Height * original.Width > target.Width * original.Height)
target.Height = target.Width * original.Height / original.Width;
else
target.Width = target.Height * original.Width / original.Height;
return target;
}
}