public PathCreator(string urlBase, ImageFormat extension, string tempFolder, string staticFolder)
        {
            UrlBase = urlBase.Replace('\\', '/');

            TempRootFolder = tempFolder;
            TempFolderFormat = null;
            TempNameFormat = "{0}{1}." + extension.ToString().ToLower();

            StaticRootFolder = staticFolder;
            StaticFolderFormat = null;
            StaticNameFormat = "{0}." + extension.ToString().ToLower();
        }
Exemplo n.º 2
0
 /// <summary>
 /// Opens up a generated image containing a QR-code within which
 /// str is encoded.
 /// 
 /// The image can be found inside the bin folder.
 /// </summary>
 /// <param name="str">Content of the generated QR-code</param>
 /// <param name="width">Width of the image</param>
 /// <param name="height">Height of the image</param>
 /// <param name="format">Format of the image file</param>
 public static void ShowQRCode(string str, int width, int height, ImageFormat format)
 {
     Bitmap bmp = GenerateQRC(str, width, height);
     string address = @"..\AdrportQR." + format.ToString();
     bmp.Save(address, format);
     System.Diagnostics.Process.Start(address);
 }
Exemplo n.º 3
0
        private static ImageMIMEType?GetMIMEType(System.Drawing.Imaging.ImageFormat imageFormat)
        {
            ImageMIMEType?toRet;
            Guid          formatGuid = imageFormat.Guid;

            if (formatGuid == ImageFormat.Bmp.Guid)
            {
                toRet = ImageMIMEType.Bmp;
            }
            else if (formatGuid == ImageFormat.Gif.Guid)
            {
                toRet = ImageMIMEType.Gif;
            }
            else if (formatGuid == ImageFormat.Jpeg.Guid)
            {
                toRet = ImageMIMEType.Jpeg;
            }
            else if (formatGuid == ImageFormat.Png.Guid)
            {
                toRet = ImageMIMEType.Png;
            }
            else
            {
                throw new ApplicationException(
                          string.Format("Not supported ImageFormat {0}", imageFormat.ToString())
                          );
            }

            return(toRet);
        }
Exemplo n.º 4
0
        public static void Set(Uri uri, Style style, ImageFormat format)
        {
            Stream stream = new WebClient().OpenRead(uri.ToString());

            if (stream == null) return;

            Image img = Image.FromStream(stream);
            string tempPath = Path.Combine(Path.GetTempPath(), "img." + format.ToString());
            img.Save(tempPath, format);

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            if (style == Style.Stretched)
            {
                key.SetValue(@"WallpaperStyle", 2.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }

            if (style == Style.Centered)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }

            if (style == Style.Tiled)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 1.ToString());
            }

            SystemParametersInfo(SpiSetdeskwallpaper,
                0,
                tempPath,
                SpifUpdateinifile | SpifSendwininichange);
        }
        /// <summary>
        /// 将Word文档转换为图片的方法(该方法基于第三方DLL),你可以像这样调用该方法:
        /// ConvertPDF2Image("F:\\PdfFile.doc", "F:\\", "ImageFile", 1, 20, ImageFormat.Png, 256);
        /// </summary>
        /// <param name="pdfInputPath">Word文件路径</param>
        /// <param name="imageOutputPath">图片输出路径,如果为空,默认值为Word所在路径</param>
        /// <param name="imageName">图片的名字,不需要带扩展名,如果为空,默认值为Word的名称</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
        /// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
        /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        public static void ConvertWordToImage(string wordInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, float resolution)
        {
            try
            {
                // open word file
                Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);

                // validate parameter
                if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密!"); }
                if (imageOutputPath.Trim().Length == 0) { imageOutputPath = Path.GetDirectoryName(wordInputPath); }
                if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); }
                if (imageName.Trim().Length == 0) { imageName = Path.GetFileNameWithoutExtension(wordInputPath); }
                if (startPageNum <= 0) { startPageNum = 1; }
                if (endPageNum > doc.PageCount || endPageNum <= 0) { endPageNum = doc.PageCount; }
                if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; }
                if (imageFormat == null) { imageFormat = ImageFormat.Png; }
                if (resolution <= 0) { resolution = 128; }

                ImageSaveOptions imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat));
                imageSaveOptions.Resolution = resolution;

                // start to convert each page
                for (int i = startPageNum; i <= endPageNum; i++)
                {
                    imageSaveOptions.PageIndex = i - 1;
                    doc.Save(Path.Combine(imageOutputPath, imageName) + "_" + i.ToString() + "." + imageFormat.ToString(), imageSaveOptions);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 6
0
		public void SetUp ()		
		{
			imageFmt = ImageFormat.Bmp; 
			imageFmtStr = imageFmt.ToString ();
		
			imgFmtConv = new ImageFormatConverter();
			imgFmtConvFrmTD = (ImageFormatConverter) TypeDescriptor.GetConverter (imageFmt);			
		}
Exemplo n.º 7
0
        public FormShowFrames(string framesPath, ImageFormat imageFormat, bool allowDeletion = true)
        {
            this.framesPath = framesPath;
            this.imageExtension = "." + imageFormat.ToString().ToLower();
            this.allowDeletion = allowDeletion;

            InitializeComponent();
        }
        /// <summary>
        /// 将PDF文档转换为图片的方法,你可以像这样调用该方法:ConvertPDF2Image("F:\\A.pdf", "F:\\", "A", 0, 0, null, 0);
        /// 因为大多数的参数都有默认值,startPageNum默认值为1,endPageNum默认值为总页数,
        /// imageFormat默认值为ImageFormat.Jpeg,resolution默认值为1
        /// </summary>
        /// <param name="pdfInputPath">PDF文件路径</param>
        /// <param name="imageOutputPath">图片输出路径</param>
        /// <param name="imageName">图片的名字,不需要带扩展名</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,默认值为PDF总页数</param>
        /// <param name="imageFormat">设置所需图片格式</param>
        /// <param name="resolution">设置图片的分辨率,数字越大越清晰,默认值为1</param>
        public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, double resolution)
        {
            Acrobat.CAcroPDDoc pdfDoc = null;
            Acrobat.CAcroPDPage pdfPage = null;
            Acrobat.CAcroRect pdfRect = null;
            Acrobat.CAcroPoint pdfPoint = null;

            // Create the document (Can only create the AcroExch.PDDoc object using late-binding)
            // Note using VisualBasic helper functions, have to add reference to DLL
            pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");

            // validate parameter
            if (!pdfDoc.Open(pdfInputPath)) { throw new FileNotFoundException(); }
            if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); }
            if (startPageNum <= 0) { startPageNum = 1; }
            if (endPageNum > pdfDoc.GetNumPages() || endPageNum <= 0) { endPageNum = pdfDoc.GetNumPages(); }
            if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; }
            if (imageFormat == null) { imageFormat = ImageFormat.Jpeg; }
            if (resolution <= 0) { resolution = 1; }

            // start to convert each page
            for (int i = startPageNum; i <= endPageNum; i++)
            {
                pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(i - 1);
                pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();
                pdfRect = (Acrobat.CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");

                int imgWidth = (int)((double)pdfPoint.x * resolution);
                int imgHeight = (int)((double)pdfPoint.y * resolution);

                pdfRect.Left = 0;
                pdfRect.right = (short)imgWidth;
                pdfRect.Top = 0;
                pdfRect.bottom = (short)imgHeight;

                // Render to clipboard, scaled by 100 percent (ie. original size)
                // Even though we want a smaller image, better for us to scale in .NET
                // than Acrobat as it would greek out small text
                pdfPage.CopyToClipboard(pdfRect, 0, 0, (short)(100 * resolution));

                IDataObject clipboardData = Clipboard.GetDataObject();

                if (clipboardData.GetDataPresent(DataFormats.Bitmap))
                {
                    Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);
                    pdfBitmap.Save(Path.Combine(imageOutputPath, imageName) + i.ToString() + "." + imageFormat.ToString(), imageFormat);
                    pdfBitmap.Dispose();
                }
            }

            pdfDoc.Close();
            Marshal.ReleaseComObject(pdfPage);
            Marshal.ReleaseComObject(pdfRect);
            Marshal.ReleaseComObject(pdfDoc);
            Marshal.ReleaseComObject(pdfPoint);

        }
Exemplo n.º 9
0
 /// <summary>
 /// コンストラクタ。
 /// </summary>
 public ScreenShot()
 {
     _dir = Option.Instance().SaveDirectory;
     _fileFmt = Option.Instance().FileNameFormat;
     _imgFmt = Option.Instance().ImageFormat;
     // 拡張子を設定する。Jpegの場合は"jpg"、それ以外は名称をそのままに小文字に変換している。
     _ext = _imgFmt.Equals(ImageFormat.Jpeg) ? "jpg" : _imgFmt.ToString().ToLower();
     _matches = Rx.Matches(_fileFmt);
 }
Exemplo n.º 10
0
		public static ImageTypeMapping ByImageFormat(ImageFormat imageFormat)
		{
			ImageTypeMapping imageTypeMapping = ImageTypeMapper.mappings.Find((ImageTypeMapping candidate) => candidate.ImageFormatEquals(imageFormat));
			if (imageTypeMapping == null)
			{
				throw new UnknownImageTypeException(imageFormat.ToString());
			}
			return imageTypeMapping;
		}
Exemplo n.º 11
0
 public bool SaveImage(Stream ms, System.Drawing.Imaging.ImageFormat format)
 {
     if (_image == null)
     {
         return(false);
     }
     try
     {
         try
         {
             if (Display.MakeTransparent &&
                 format != ImageFormat.Jpeg &&
                 format != ImageFormat.Gif)
             {
                 _image.MakeTransparent(Display.TransparentColor);
             }
         }
         catch (Exception ex)
         {
             if (this.MapServer != null)
             {
                 this.MapServer.Log(
                     "RenderRasterLayerThread", loggingMethod.error,
                     "Image.MakeTransparent\n'\nFormat=" + format.ToString() + "\n" +
                     ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
             }
         }
         _image.Save(ms, format);
         _image.Dispose();
         _image = null;
         return(true);
     }
     catch (Exception ex)
     {
         if (this.MapServer != null)
         {
             this.MapServer.Log(
                 "RenderRasterLayerThread", loggingMethod.error,
                 "Image.Save\n'\nFormat=" + format.ToString() + "\n" +
                 ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
         }
         return(false);
     }
 }
Exemplo n.º 12
0
 public static string SearchingKeyInImgFormats(ImageFormat value)
 {
     var resultKey = value.ToString();
     foreach(var el in ImgFormats)
     {
         if (value == el.Value)
             resultKey = el.Key;
     }
     return resultKey;
 }
Exemplo n.º 13
0
 public String SaveImage(string title, ImageFormat format)
 {
     string pathTmp = "";
     count++;
     if (bitmap != null)
     {
         Console.Write(format.ToString());
         pathTmp = @"c:\\saves\\" + title + "\\" + count + ".jpeg";
         bitmap.Save(pathTmp, ImageFormat.Jpeg);
     }
     return pathTmp;
 }
Exemplo n.º 14
0
        public static string ToBase64ImageTag(this Bitmap bmp, ImageFormat imageFormat)
        {
            string imgTag = string.Empty;
            string base64String = string.Empty;

            base64String = bmp.ToBase64String(imageFormat);

            imgTag = "<img src=\"data:image/" + imageFormat.ToString() + ";base64,";
            imgTag += base64String + "\" ";
            imgTag += "width=\"" + bmp.Width.ToString() + "\" ";
            imgTag += "height=\"" + bmp.Height.ToString() + "\" />";

            return imgTag;
        }
Exemplo n.º 15
0
 /// <summary>
 /// Returns the correct file extension for the given <see cref="T:System.Drawing.Imaging.ImageFormat"/>.
 /// </summary>
 /// <param name="imageFormat">
 /// The <see cref="T:System.Drawing.Imaging.ImageFormat"/> to return the extension for.
 /// </param>
 /// <returns>
 /// The correct file extension for the given <see cref="T:System.Drawing.Imaging.ImageFormat"/>.
 /// </returns>
 public static string GetExtensionFromImageFormat(ImageFormat imageFormat)
 {
     switch (imageFormat.ToString())
     {
         case "Gif":
             return ".gif";
         case "Bmp":
             return ".bmp";
         case "Png":
             return ".png";
         default:
             return ".jpg";
     }
 }
Exemplo n.º 16
0
        public void SaveFractalImage(ImageFormat format,string name)
        {
            if(_renderViewPresenter.ActualFractalImage != null)
            {
                FolderBrowserDialog d = new FolderBrowserDialog();
                if (d.ShowDialog() == DialogResult.OK)
                {
                    string savePath = string.Format("{0}\\{1}.{2}",
                        d.SelectedPath,
                        name,
                        format.ToString());

                    _renderViewPresenter.ActualFractalImage.Save(savePath);
                }
            }
        }
Exemplo n.º 17
0
 /// <summary>
 /// ImageFormatから拡張子を求める。
 /// </summary>
 public static string DetermineFileExtension(ImageFormat format)
 {
     try
     {
         return ImageCodecInfo.GetImageEncoders()
                 .First(x => x.FormatID == format.Guid)
                 .FilenameExtension
                 .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                 .First()
                 .Trim('*')
                 .ToLower();
     }
     catch (Exception)
     {
         return "." + format.ToString().ToLower();
     }
 }
Exemplo n.º 18
0
 internal static MagickFormat GetFormat(ImageFormat format)
 {
   if (format == ImageFormat.Bmp)
     return MagickFormat.Bmp;
   else if (format == ImageFormat.Gif)
     return MagickFormat.Gif;
   else if (format == ImageFormat.Icon)
     return MagickFormat.Icon;
   else if (format == ImageFormat.Jpeg)
     return MagickFormat.Jpeg;
   else if (format == ImageFormat.Png)
     return MagickFormat.Png;
   else if (format == ImageFormat.Tiff)
     return MagickFormat.Tiff;
   else
     throw new NotSupportedException("Unsupported image format: " + format.ToString());
 }
        public static string BuildImageTag(Image image, ImageFormat format)
        {
            // IE8 limit to 32 Kb
            var ms = new MemoryStream();
            image.Save(ms, format);
            if (ms.Length/1024 > 32)
            {
                throw new ArgumentOutOfRangeException("image", "IE8 cannot support Data Uri string great than 32KB");
            }

            var base64String = Convert.ToBase64String(ms.ToArray());
            ms.Dispose();
            var stringFormat = "image/" + format.ToString().ToLower();
            return string.Format(
                "<img src=\"data:{0};base64,{1}\" alt=\"Base64 encoded image\" width=\"{2}\" height=\"{3}\" />",
                stringFormat, base64String, image.Width, image.Height);
        }
        /// <summary>
        /// 将PDF文档转换为图片的方法
        /// </summary>
        /// <param name="pdfInputPath">PDF文件路径</param>
        /// <param name="imageOutputPath">图片输出路径</param>
        /// <param name="imageName">生成图片的名字</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
        /// <param name="imageFormat">设置所需图片格式</param>
        /// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
        public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
        {
            FileStream fs = new FileStream(pdfInputPath, FileMode.Open);

            TallComponents.PDF.Rasterizer.Document doc = new TallComponents.PDF.Rasterizer.Document(fs);

            if (!Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }

            // validate pageNum
            if (startPageNum <= 0)
            {
                startPageNum = 1;
            }

            if (endPageNum > doc.Pages.Count)
            {
                endPageNum = doc.Pages.Count;
            }

            if (startPageNum > endPageNum)
            {
                int tempPageNum = startPageNum;
                startPageNum = endPageNum;
                endPageNum = startPageNum;
            }

            // start to convert each page
            for (int i = startPageNum; i <= endPageNum; i++)
            {
                using (FileStream fs1 = File.Create(imageOutputPath + @"~temp" + i + ".tmp"))
                {
                    TallComponents.PDF.Rasterizer.ConvertToTiffOptions option = new TallComponents.PDF.Rasterizer.ConvertToTiffOptions();
                    doc.Pages[i].ConvertToTiff(fs1, option);
                    System.Drawing.Image img = System.Drawing.Image.FromStream(fs1);
                    img.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat);
                }

                File.Delete(imageOutputPath + @"~temp" + i + ".tmp");
            }

            fs.Dispose();
        }
        /// <summary>
        /// 将PDF文档转换为图片的方法
        /// </summary>
        /// <param name="pdfInputPath">PDF文件路径</param>
        /// <param name="imageOutputPath">图片输出路径</param>
        /// <param name="imageName">生成图片的名字</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
        /// <param name="imageFormat">设置所需图片格式</param>
        /// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
        public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
        {

            global::SautinSoft.PdfFocus pdfFocus = new global::SautinSoft.PdfFocus();

            pdfFocus.OpenPdf(pdfInputPath);

            if (!Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }

            // validate pageNum
            if (startPageNum <= 0)
            {
                startPageNum = 1;
            }

            if (endPageNum > pdfFocus.PageCount)
            {
                endPageNum = pdfFocus.PageCount;
            }

            if (startPageNum > endPageNum)
            {
                int tempPageNum = startPageNum;
                startPageNum = endPageNum;
                endPageNum = startPageNum;
            }

            // start to convert each page
            for (int i = startPageNum; i <= endPageNum; i++)
            {
                byte[] img = pdfFocus.ToImage(i);
                using (FileStream fs1 = File.Create(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString()))
                {
                    fs1.Write(img, 0, img.Length);
                }
            }

            pdfFocus.ClosePdf();
        }
Exemplo n.º 22
0
        //--
        //-- takes a screenshot of the desktop and saves to filename and format specified
        //--
        private static void TakeScreenshotPrivate(string strFilename)
        {
            Rectangle objRectangle       = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            Bitmap    objBitmap          = new Bitmap(objRectangle.Right, objRectangle.Bottom);
            Graphics  objGraphics        = null;
            IntPtr    hdcDest            = default(IntPtr);
            int       hdcSrc             = 0;
            const int SRCCOPY            = 0xcc0020;
            string    strFormatExtension = null;

            //objGraphics = objGraphics.FromImage(objBitmap);
            objGraphics = Graphics.FromImage(objBitmap);

            //-- get a device context to the windows desktop and our destination  bitmaps
            hdcSrc  = GetDC(0);
            hdcDest = objGraphics.GetHdc();
            //-- copy what is on the desktop to the bitmap
            BitBlt(hdcDest.ToInt32(), 0, 0, objRectangle.Right, objRectangle.Bottom, hdcSrc, 0, 0, SRCCOPY);
            //-- release device contexts
            objGraphics.ReleaseHdc(hdcDest);
            ReleaseDC(0, hdcSrc);

            strFormatExtension = _ScreenshotImageFormat.ToString().ToLower();
            if (System.IO.Path.GetExtension(strFilename) != "." + strFormatExtension)
            {
                strFilename += "." + strFormatExtension;
            }
            switch (strFormatExtension)
            {
            case "jpeg":
                BitmapToJPEG(objBitmap, strFilename, 80);
                break;

            default:
                objBitmap.Save(strFilename, _ScreenshotImageFormat);
                break;
            }

            //-- save the complete path/filename of the screenshot for possible later use
            _strScreenshotFullPath = strFilename;
        }
Exemplo n.º 23
0
        //Definition definition)
        /// <summary>
        /// 将PDF文档转换为图片的方法
        /// </summary>
        /// <param name="pdfInputPath">PDF文件路径</param>
        /// <param name="imageOutputPath">图片输出路径</param>
        /// <param name="imageName">生成图片的名字</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
        /// <param name="imageFormat">设置所需图片格式</param>
        /// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
        public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, int definition)
        {
            PDFFile pdfFile = PDFFile.Open(pdfInputPath);

            if (!Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }

            // validate pageNum
            if (startPageNum <= 0)
            {
                startPageNum = 1;
            }

            if (endPageNum > pdfFile.PageCount)
            {
                endPageNum = pdfFile.PageCount;
            }

            if (startPageNum > endPageNum)
            {
                int tempPageNum = startPageNum;
                startPageNum = endPageNum;
                endPageNum = startPageNum;
            }

            // start to convert each page
            for (int i = startPageNum; i <= endPageNum; i++)
            {
                Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition);
                pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat);
                //pageImage.Save(imageOutputPath + imageName , imageFormat);
                pageImage.Dispose();
            }

            pdfFile.Dispose();
        }
Exemplo n.º 24
0
        public void Process(FileInfo image, string outPath, string prefix, string suffix, ImageFormat format)
        {
            LoggingService.WriteLine("Processing {0}", image.Name);
            var outFileName = string.Format("{0}{1}{2}", prefix, Path.GetFileNameWithoutExtension(image.FullName), suffix);
            var rootDir = string.IsNullOrWhiteSpace(outPath) ? Path.GetDirectoryName(_here) : new DirectoryInfo(outPath).FullName;
            var extension = format == null ? image.Extension : string.Format(".{0}", format.ToString().ToLower());
            LoggingService.WriteVerbose("New File Name: {0}{1}", outFileName, extension);


            int defaultHeight;
            int defaultWidth;

            using (var img = Image.FromFile(image.FullName))
            {
                defaultHeight = img.Height;
                defaultWidth = img.Width;
            }

            LoggingService.WriteVerbose("Original Dimensions: {0}W by {1}H", defaultWidth, defaultHeight);

            var expectedImages = ImageHelper.BuildImageInfo(rootDir, outFileName, extension);

            DirectoryHelper.SetupPaths(expectedImages, _dry);

            var codec = ImageHelper.GetImageCodecInfo(format);

            foreach (var expectedImage in expectedImages)
            {
                var path = expectedImage.Value.Item1;
                var scale = expectedImage.Value.Item2;
                var scaledWidth = (int) Math.Ceiling(defaultWidth/scale);
                var scaledHeight = (int) Math.Ceiling(defaultHeight/scale);
                var scaledImage = _scalerService.Scale(scaledWidth, scaledHeight, image.FullName);
                scaledImage.Save(path, codec, _dry);

                LoggingService.WriteVerbose("New Dimensions for {0}: {1}W by {2}H", expectedImage.Key, scaledWidth, scaledHeight);
            }
            LoggingService.WriteLine();
        }
Exemplo n.º 25
0
        }        //end CopyFrameFromInternalBitmap

        public bool SaveInternalBitmap(string sFileName, System.Drawing.Imaging.ImageFormat imageformat)
        {
            bool bGood = true;

            try {
                bmpLoaded.Save(sFileName, imageformat);
            }
            catch (Exception exn) {
                bGood = false;
                RReporting.ShowExn(exn, "SaveInternalBitmap(\"" + sFileName + "\"," + imageformat.ToString() + ")");
            }
            return(bGood);
        }
Exemplo n.º 26
0
 private string HTMLGetImage(int PageNumber, int CurrentPage, int ImageNumber, string hash, bool Base,
                             System.Drawing.Image Metafile, MemoryStream PictureStream)
 {
     if (FPictures)
     {
         System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Bmp;
         if (FImageFormat == ImageFormat.Png)
         {
             format = System.Drawing.Imaging.ImageFormat.Png;
         }
         else if (FImageFormat == ImageFormat.Jpeg)
         {
             format = System.Drawing.Imaging.ImageFormat.Jpeg;
         }
         else if (FImageFormat == ImageFormat.Gif)
         {
             format = System.Drawing.Imaging.ImageFormat.Gif;
         }
         StringBuilder ImageFileNameBuilder = new StringBuilder(48);
         string        ImageFileName        = ImageFileNameBuilder.Append(Path.GetFileName(FTargetFileName)).
                                              Append(".").Append(hash).
                                              Append(".").Append(format.ToString().ToLower()).ToString();
         if (!FWebMode)
         {
             if (Base)
             {
                 if (Metafile != null)
                 {
                     using (FileStream ImageFileStream =
                                new FileStream(FTargetPath + ImageFileName, FileMode.Create))
                         Metafile.Save(ImageFileStream, format);
                 }
                 else if (PictureStream != null)
                 {
                     if (FFormat == HTMLExportFormat.HTML)
                     {
                         string   fileName = FTargetPath + ImageFileName;
                         FileInfo info     = new FileInfo(fileName);
                         if (!(info.Exists && info.Length == PictureStream.Length))
                         {
                             using (FileStream ImageFileStream =
                                        new FileStream(fileName, FileMode.Create))
                                 PictureStream.WriteTo(ImageFileStream);
                         }
                     }
                     else
                     {
                         PicsArchiveItem item;
                         item.FileName = ImageFileName;
                         item.Stream   = PictureStream;
                         bool founded = false;
                         for (int i = 0; i < FPicsArchive.Count; i++)
                         {
                             if (item.FileName == FPicsArchive[i].FileName)
                             {
                                 founded = true;
                                 break;
                             }
                         }
                         if (!founded)
                         {
                             FPicsArchive.Add(item);
                         }
                     }
                 }
                 GeneratedFiles.Add(FTargetPath + ImageFileName);
             }
             if (FSubFolder && FSinglePage && !FNavigator)
             {
                 return(ExportUtils.HtmlURL(FSubFolderPath + ImageFileName));
             }
             else
             {
                 return(ExportUtils.HtmlURL(ImageFileName));
             }
         }
         else
         {
             if (Base)
             {
                 FPages[CurrentPage].Pictures.Add(PictureStream);
                 FPages[CurrentPage].Guids.Add(hash);
             }
             return(FWebImagePrefix + "=" + hash);
         }
     }
     else
     {
         return(String.Empty);
     }
 }
Exemplo n.º 27
0
        internal static void Screenshot(string targetFolder, string fileName, ImageFormat imgFormat, bool activeWindowOnly)
        {
            try
            {
                if (targetFolder.Length > 0 && fileName.Length > 0 && imgFormat != null)
                {
                    Bitmap bitmap = new Bitmap(1, 1);
                    Rectangle bounds;
                    if (activeWindowOnly)
                    {
                        WinApi.RECT srcRect;
                        if (WinApi.GetWindowRect(Client.Tibia.MainWindowHandle, out srcRect) != null)
                        {
                            int width = srcRect.right - srcRect.left;
                            int height = srcRect.bottom - srcRect.top;

                            bitmap = new Bitmap(width, height);
                            Graphics gr = Graphics.FromImage(bitmap);
                            gr.CopyFromScreen(srcRect.left, srcRect.top,
                                            0, 0, new Size(width, height),
                                            CopyPixelOperation.SourceCopy);
                        }

                    }
                    else
                    {
                        bounds = Screen.GetBounds(Point.Empty);
                        bitmap = new Bitmap(bounds.Width, bounds.Height);
                        using (Graphics gr = Graphics.FromImage(bitmap))
                        {
                            gr.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                        }
                    }
                    bitmap.Save(targetFolder + fileName + DateTime.Now.ToString("-yyyy-MM-dd~HH-mm-ss") + "." + imgFormat.ToString().ToLower(), imgFormat);
                }
            }
            catch (Exception ex)
            {
                Utils.ExceptionHandler(ex);
            }
        }
Exemplo n.º 28
0
		/// <summary>
		/// Determine name of new file and, for a new media object, makes sure it is unique in the directory. (Example: If original = puppy.jpg, 
		/// thumbnail = zOpt_puppy.jpg)
		/// </summary>
		/// <param name="optimizedPath">The path to the directory where the optimized file is to be created.</param>
		/// <param name="imgFormat">The image format of the thumbnail.</param>
		/// <returns>Returns the name of the new thumbnail file name and, for a new media object, makes sure it is unique in the directory.</returns>
		private string GenerateNewFilename(string optimizedPath, ImageFormat imgFormat)
		{
			string filenamePrefix = GalleryServerPro.Configuration.ConfigManager.GetGalleryServerProConfigSection().Core.OptimizedFileNamePrefix;
			string nameWithoutExtension = Path.GetFileNameWithoutExtension(this._imageObject.Original.FileInfo.Name);
			string optimizedFilename = string.Format(CultureInfo.CurrentCulture, "{0}{1}.{2}", filenamePrefix, nameWithoutExtension, imgFormat.ToString().ToLower(CultureInfo.CurrentCulture));

			if (this._imageObject.IsNew)
			{
				// Since this is a new media object, make sure the file is unique in the directory. For existing media objects, we'll just
				// overwrite the file (if it exists).
				optimizedFilename = HelperFunctions.ValidateFileName(optimizedPath, optimizedFilename);
			}

			return optimizedFilename;
		}
Exemplo n.º 29
0
        /// <summary>
        /// Converts an ImageFormat value to a Web Content Type
        /// </summary>
        /// <param name="formatGuid"></param>
        /// <returns></returns>
        public static string ImageFormatToContentType(ImageFormat format)
        {
            string ct = null;

            if (format.Equals(ImageFormat.Png))
                ct = "image/png";
            else if (format.Equals(ImageFormat.Jpeg))
                ct = "image/jpeg";
            else if (format.Equals(ImageFormat.Gif))
                ct = "image/gif";
            else if (format.Equals(ImageFormat.Tiff))
                ct = "image/tiff";
            else if (format.Equals(ImageFormat.Bmp))
                ct = "image/bmp";
            else if (format.Equals(ImageFormat.Icon))
                ct = "image/x-icon";
            else if (format.Equals(ImageFormat.Wmf))
                ct = "application/x-msmetafile";
            else
                throw new InvalidOperationException(string.Format(Resources.ERROR_UnableToConvertImageFormatToContentType, format.ToString()));

            return ct;
        }
Exemplo n.º 30
0
        private void outputFormatCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Format selection
            imageFormatPicked = null;

            switch (imageFormatList.SelectedItem.ToString())
            {

                case "Bmp":
                    imageFormatPicked = ImageFormat.Bmp;
                    break;

                case "Emf":
                    imageFormatPicked = ImageFormat.Emf;
                    break;

                case "Exif":
                    imageFormatPicked = ImageFormat.Exif;
                    break;

                case "Gif":
                    imageFormatPicked = ImageFormat.Gif;
                    break;

                case "Icon":
                    imageFormatPicked = ImageFormat.Icon;
                    break;

                case "Jpeg":
                    imageFormatPicked = ImageFormat.Jpeg;
                    break;

                case "MemoryBmp":
                    imageFormatPicked = ImageFormat.MemoryBmp;
                    break;

                case "Png":
                    imageFormatPicked = ImageFormat.Png;
                    break;

                case "Tiff":
                    imageFormatPicked = ImageFormat.Tiff;
                    break;

                case "Wmf":
                    imageFormatPicked = ImageFormat.Wmf;
                    break;

            }

            //Output format selection
            string directoryToOutput = directory + (directory.EndsWith("\\") ? "" : "\\");

            if (outputFormatCombo.SelectedItem == null)
            {
                return;
            }

            switch (outputFormatCombo.SelectedItem.ToString())
            {
                case "Number":
                    directoryToOutput += count;
                    break;

                case "Date/Time":
                    directoryToOutput += "M" + DateTime.Now.Month + "D" + DateTime.Now.Day + "Y" + DateTime.Now.Year + "H" + DateTime.Now.Hour + "Mi" + DateTime.Now.Minute + "S" + DateTime.Now.Second;
                    break;

                case "Custom":
                    directoryToOutput = outputExampleTextField.Text;
                    break;
            }

            outputExampleTextField.Text = directoryToOutput + "." + imageFormatPicked.ToString().ToLower();
        }
Exemplo n.º 31
0
        /// <summary>
        /// Initialise a new FreeImage class from a System.Drawing.Bitmap
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="imageFormat"></param>
        public FreeImage(Bitmap bitmap, ImageFormat imageFormat)
        {
            FREE_IMAGE_FORMAT fif = ImageFormatToFIF(imageFormat);
            if (fif == FREE_IMAGE_FORMAT.FIF_UNKNOWN)
            {
                throw new Exception("Image format \"" + imageFormat.ToString() + "\" is not supported");
            }

            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, imageFormat);
            ms.Flush();

            byte[] buffer = new byte[((int)(ms.Length - 1)) + 1];
            ms.Position = 0;
            ms.Read(buffer, 0, (int)ms.Length);
            ms.Close();

            IntPtr dataPtr = Marshal.AllocHGlobal(buffer.Length);
            Marshal.Copy(buffer, 0, dataPtr, buffer.Length);

            m_MemPtr = (IntPtr)FreeImageApi.OpenMemory(dataPtr, buffer.Length);
            m_Handle = FreeImageApi.LoadFromMemory(fif, (uint)m_MemPtr, 0);
        }
Exemplo n.º 32
0
 private FREE_IMAGE_FORMAT ImageFormatToFIF(ImageFormat imageFormat)
 {
     string fmt = imageFormat.ToString().ToLower();
     if (fmt == "bmp")
     {
         return FREE_IMAGE_FORMAT.FIF_BMP;
     }
     if (fmt == "jpg")
     {
         return FREE_IMAGE_FORMAT.FIF_JPEG;
     }
     return FREE_IMAGE_FORMAT.FIF_UNKNOWN;
 }
Exemplo n.º 33
0
        public override System.IO.Stream GetStream()
        {
            if (RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
            {
                ContentType = "image/jpeg";
            }
            else if (RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
            {
                ContentType = "image/gif";
            }
            else if (RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
            {
                ContentType = "image/bmp";
            }
            else if (RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
            {
                ContentType = "image/tiff";
            }
            else if (RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
            {
                ContentType = "image/x-png";
            }
            else if (RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Wmf))
            {
                ContentType = "image/wmf";
            }
            else
            {
                throw (new NotSupportedException("Unsupported image format \'" + RawFormat.ToString() + "\'"));
            }

            if (LowQuality && ContentType == "image/jpeg")
            {
                try
                {
                    ImageCodecInfo    myImageCodecInfo = GetEncoderInfo(ImageFormat.Jpeg);
                    Encoder           myEncoder;
                    EncoderParameter  myEncoderParameter;
                    EncoderParameters myEncoderParameters;


                    // Create an Encoder object based on the GUID
                    // for the Quality parameter category.
                    myEncoder = Encoder.Quality;

                    // Create an EncoderParameters object.
                    // An EncoderParameters object has an array of EncoderParameter
                    // objects. In this case, there is only one
                    // EncoderParameter object in the array.
                    myEncoderParameters = new EncoderParameters(1);


                    MemoryStream mem = new MemoryStream();

                    // Save the bitmap as a JPEG file with quality level 25.
                    myEncoderParameter           = new EncoderParameter(myEncoder, 25);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    Bitmap.Save(mem, myImageCodecInfo, myEncoderParameters);

                    //move position to begin
                    mem.Seek(0, SeekOrigin.Begin);
                    return(mem);
                }
                catch (Exception)
                {
                    MemoryStream mem = new MemoryStream();
                    Bitmap.Save(mem, RawFormat);

                    //move position to begin
                    mem.Seek(0, SeekOrigin.Begin);

                    return(mem);
                }
            }
            else
            {
                MemoryStream mem = new MemoryStream();
                Bitmap.Save(mem, RawFormat);

                //move position to begin
                mem.Seek(0, SeekOrigin.Begin);
                return(mem);
            }
        }
Exemplo n.º 34
0
		private FreeImageFormat ImageFormatToFIF(ImageFormat imageFormat)
		{
			string fmt = imageFormat.ToString().ToLower();
			if (fmt == "bmp")
			{
				return FreeImageFormat.Bmp;
			}
			if (fmt == "jpg")
			{
				return FreeImageFormat.Jpg;
			}
			return FreeImageFormat.Unknown;
		}
Exemplo n.º 35
0
        /// <summary>
        /// Returns the correct file extension for the given <see cref="T:System.Drawing.Imaging.ImageFormat"/>.
        /// </summary>
        /// <param name="imageFormat">
        /// The <see cref="T:System.Drawing.Imaging.ImageFormat"/> to return the extension for.
        /// </param>
        /// <param name="originalExtension">
        /// The original Extension.
        /// </param>
        /// <returns>
        /// The correct file extension for the given <see cref="T:System.Drawing.Imaging.ImageFormat"/>.
        /// </returns>
        public static string GetExtensionFromImageFormat(ImageFormat imageFormat, string originalExtension)
        {
            switch (imageFormat.ToString())
            {
                case "Gif":
                    return ".gif";
                case "Bmp":
                    return ".bmp";
                case "Png":
                    return ".png";
                case "Tif":
                case "Tiff":
                    if (!string.IsNullOrWhiteSpace(originalExtension) && originalExtension.ToUpperInvariant() == ".TIFF")
                    {
                        return ".tiff";
                    }

                    return ".tif";
                default:
                    if (!string.IsNullOrWhiteSpace(originalExtension) && originalExtension.ToUpperInvariant() == ".JPEG")
                    {
                        return ".jpeg";
                    }

                    return ".jpg";
            }
        }
Exemplo n.º 36
0
 public static String GetImageExt(ImageFormat formatType)
 {
     //Only support conversin to jpg, gif and png for web images
     if (formatType == ImageFormat.Jpeg)
     {
         return "jpg";
     }
     if (formatType == ImageFormat.Gif)
     {
         return "gif";
     }
     if (formatType == ImageFormat.Png)
     {
         return "png";
     }
     else
     {
         throw new Exception(Language.Message("UnknowFormatGivenForConversion", formatType.ToString()));
     }
 }
Exemplo n.º 37
0
 private static string GetFilenameExtension(ImageFormat format)
 {
     return(ImageCodecInfo.GetImageEncoders().FirstOrDefault(x => x.FormatID == format.Guid)?.FilenameExtension.Split(';')[0].Replace("*.", "").ToLower() ?? format.ToString());
 }