Ejemplo n.º 1
0
        public Webcam(string ocu_ipAddress, CameraConfiguration config)
        {
            this.config = config;
            FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices.Count < 1)
                throw new Exception("No video input devices available");
            if (!string.IsNullOrEmpty(config.DeviceName))
                videoSource = new VideoCaptureDevice(config.DeviceName);
                //videoSource = new VideoCaptureDevice(videoDevices[1].MonikerString);
            else
            {
                videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
            }

            updateWorker = new Timer();
            updateWorker.Elapsed += new ElapsedEventHandler(updateWorker_Elapsed);
            FrameRate = config.RCU_To_OCU_Framerate;
            JPEGQuality = config.JPEGQuality;
            isActive = false;
            jpegCodec = GetEncoderInfo("image/jpeg");
            videoSource.DesiredFrameSize = new Size(320, 240);
            videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
            udp_sender = new Comms.UDP_Sender(ocu_ipAddress, config.SendPort);
            raw_frame_queue = new Utility.UpdateQueue<byte[]>(-1);
        }
Ejemplo n.º 2
0
 static void ResizeImage(string SourceFile, string DestinationFile, ImageCodecInfo encoder, EncoderParameters parameters)
 {
     try
     {
         using (Image Source = Image.FromFile(SourceFile))
         {
             int NewWidth, NewHeight;
             if (Source.Width > ResizeMaxPixels && Source.Width >= Source.Height)
             {
                 NewWidth = ResizeMaxPixels;
                 NewHeight = (Source.Height * ResizeMaxPixels) / Source.Width;
                 using (Image Dest = ResizeImage(Source, NewWidth, NewHeight))
                     Dest.Save(DestinationFile, encoder, parameters);
             }
             else if (Source.Height > ResizeMaxPixels && Source.Height >= Source.Width)
             {
                 NewWidth = (Source.Width * ResizeMaxPixels) / Source.Height;
                 NewHeight = ResizeMaxPixels;
                 using (Image Dest = ResizeImage(Source, NewWidth, NewHeight))
                     Dest.Save(DestinationFile, encoder, parameters);
             }
             else
             {
                 // no need for resize
                 Source.Save(DestinationFile, encoder, parameters);
             }
         }
     }
     catch (Exception e)
     {
         File.Delete(DestinationFile); // make sure destination file doesn't exist anymore
         Console.WriteLine("Error: " + e.Message);
     }
 }
 private static ImageCodecInfo[] ConvertFromMemory(IntPtr memoryStart, int numCodecs)
 {
     ImageCodecInfo[] infoArray = new ImageCodecInfo[numCodecs];
     for (int i = 0; i < numCodecs; i++)
     {
         IntPtr lparam = (IntPtr) (((long) memoryStart) + (Marshal.SizeOf(typeof(ImageCodecInfoPrivate)) * i));
         ImageCodecInfoPrivate data = new ImageCodecInfoPrivate();
         System.Drawing.UnsafeNativeMethods.PtrToStructure(lparam, data);
         infoArray[i] = new ImageCodecInfo();
         infoArray[i].Clsid = data.Clsid;
         infoArray[i].FormatID = data.FormatID;
         infoArray[i].CodecName = Marshal.PtrToStringUni(data.CodecName);
         infoArray[i].DllName = Marshal.PtrToStringUni(data.DllName);
         infoArray[i].FormatDescription = Marshal.PtrToStringUni(data.FormatDescription);
         infoArray[i].FilenameExtension = Marshal.PtrToStringUni(data.FilenameExtension);
         infoArray[i].MimeType = Marshal.PtrToStringUni(data.MimeType);
         infoArray[i].Flags = (ImageCodecFlags) data.Flags;
         infoArray[i].Version = data.Version;
         infoArray[i].SignaturePatterns = new byte[data.SigCount][];
         infoArray[i].SignatureMasks = new byte[data.SigCount][];
         for (int j = 0; j < data.SigCount; j++)
         {
             infoArray[i].SignaturePatterns[j] = new byte[data.SigSize];
             infoArray[i].SignatureMasks[j] = new byte[data.SigSize];
             Marshal.Copy((IntPtr) (((long) data.SigMask) + (j * data.SigSize)), infoArray[i].SignatureMasks[j], 0, data.SigSize);
             Marshal.Copy((IntPtr) (((long) data.SigPattern) + (j * data.SigSize)), infoArray[i].SignaturePatterns[j], 0, data.SigSize);
         }
     }
     return infoArray;
 }
    protected static void KucukBoyut(System.Drawing.Image orjinalFoto, int boyut, string dosyaAdi)
    {
        System.Drawing.Bitmap   islenmisFotograf = null;
        System.Drawing.Graphics grafik           = null;

        int hedefGenislik = boyut;
        int hedefYukseklik = boyut;
        int new_width, new_height;

        new_height     = (int)Math.Round(((float)orjinalFoto.Height * (float)boyut) / (float)orjinalFoto.Width);
        new_width      = hedefGenislik;
        hedefYukseklik = new_height;
        new_width      = new_width > hedefGenislik ? hedefGenislik : new_width;
        new_height     = new_height > hedefYukseklik ? hedefYukseklik : new_height;
        if (new_height > 210)
        {
            hedefYukseklik = 210;
        }
        islenmisFotograf = new System.Drawing.Bitmap(hedefGenislik, hedefYukseklik);
        grafik           = System.Drawing.Graphics.FromImage(islenmisFotograf);
        grafik.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, hedefGenislik, hedefYukseklik));
        int paste_x = (hedefGenislik - new_width) / 2;
        int paste_y = (hedefYukseklik - new_height) / 2;

        grafik.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        grafik.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        grafik.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.Default;

        System.Drawing.Imaging.ImageCodecInfo    codec   = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L);

        grafik.DrawImage(orjinalFoto, paste_x, paste_y, new_width, new_height);
        islenmisFotograf.Save(HttpContext.Current.Server.MapPath("../Urunler/Logo/" + dosyaAdi), codec, eParams);
    }
Ejemplo n.º 5
0
 static ExportBitmapCommand()
 {
     foreach (ImageCodecInfo ici in ImageCodecInfo.GetImageEncoders())
     {
         _jpegEncoder = ici;
     }
 }
Ejemplo n.º 6
0
 public static System.Drawing.Imaging.ImageCodecInfo GetJPEGCodec()
 {
     System.Drawing.Imaging.ImageCodecInfo jpegcodec;
     if (ImageHelper._isloadjpegcodec)
     {
         jpegcodec = ImageHelper._jpegcodec;
     }
     else
     {
         System.Drawing.Imaging.ImageCodecInfo[] imageEncoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
         System.Drawing.Imaging.ImageCodecInfo[] array         = imageEncoders;
         for (int i = 0; i < array.Length; i++)
         {
             System.Drawing.Imaging.ImageCodecInfo imageCodecInfo = array[i];
             if (imageCodecInfo.MimeType.IndexOf("jpeg") > -1)
             {
                 ImageHelper._jpegcodec = imageCodecInfo;
                 break;
             }
         }
         ImageHelper._isloadjpegcodec = true;
         jpegcodec = ImageHelper._jpegcodec;
     }
     return(jpegcodec);
 }
Ejemplo n.º 7
0
        public static Stream ResizeImage(Stream originalImage, int canvasWidth, int canvasHeight)
        {
            using (Image img = Image.FromStream(originalImage))
            {
                Image resizedImage = ResizeImage(img, canvasWidth, canvasHeight);


                System.Drawing.Imaging.ImageCodecInfo info = ImageCodecInfo.GetImageEncoders()
                                                             .Where(codec => String.Compare(codec.FilenameExtension, "*.png", true) == 0)
                                                             .FirstOrDefault();

                //MemoryStream stream = new MemoryStream();

                MemoryStream stream = new MemoryStream();
                if (info != null)
                {
                    EncoderParameters encoderParameters;
                    encoderParameters          = new EncoderParameters(1);
                    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                                                                      100L);


                    resizedImage.Save(stream, info, encoderParameters);
                }

                return(stream);
            }
        }
Ejemplo n.º 8
0
        } // end of color

        //使用方法调用GenerateHighThumbnail()方法即可
        //参数oldImagePath表示要被缩放的图片路径
        //参数newImagePath表示缩放后保存的图片路径
        //参数width和height分别是缩放范围宽和高
        public static void GenerateHighThumbnail(string oldImagePath, string newImagePath, int width, int height)
        {
            System.Drawing.Image oldImage = System.Drawing.Image.FromFile(oldImagePath);
            int newWidth  = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width;
            int newHeight = AdjustSize(width, height, oldImage.Width, oldImage.Height).Height;

            //。。。。。。。。。。。
            System.Drawing.Image  thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            System.Drawing.Bitmap bm             = new System.Drawing.Bitmap(thumbnailImage);
            //处理JPG质量的函数
            System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
            if (ici != null)
            {
                System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
                ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
                bm.Save(newImagePath, ici, ep);
                //释放所有资源,不释放,可能会出错误。
                ep.Dispose();
                ep = null;
            }
            ici = null;
            bm.Dispose();
            bm = null;
            thumbnailImage.Dispose();
            thumbnailImage = null;
            oldImage.Dispose();
            oldImage = null;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 将<paramref name="sourceStream"/>压缩大小
        /// </summary>
        /// <param name="sourceStream"></param>
        /// <param name="ouputStream"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void Compress(Stream sourceStream, Stream ouputStream, int width, int height, bool highQuality)
        {
            System.Drawing.Image source = null;
            Graphics             gdiobj = null;

            try
            {
                source = System.Drawing.Image.FromStream(sourceStream);
                using (Bitmap img = new Bitmap(width, height))
                {
                    img.SetResolution(source.HorizontalResolution, source.VerticalResolution);
                    gdiobj = Graphics.FromImage(img);
                    gdiobj.CompositingQuality = highQuality ? CompositingQuality.HighQuality : CompositingQuality.HighSpeed;
                    gdiobj.SmoothingMode      = highQuality ? SmoothingMode.HighQuality : SmoothingMode.HighSpeed;
                    gdiobj.InterpolationMode  = highQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Low;
                    gdiobj.PixelOffsetMode    = highQuality? PixelOffsetMode.HighQuality: PixelOffsetMode.HighSpeed;
                    gdiobj.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(0, System.Drawing.Color.Transparent)), 0, 0, width, height);
                    Rectangle destrect = new Rectangle(0, 0, width, height);
                    gdiobj.DrawImage(source, destrect, 0, 0, source.Width,
                                     source.Height, GraphicsUnit.Pixel);

                    using (System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1))
                    {
                        ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)1);
                        if (!highQuality)
                        {
                            img.Save(ouputStream, ImageFormat.Png);
                        }
                        else
                        {
                            System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/png");
                            if (ici != null)
                            {
                                img.Save(ouputStream, ici, ep);
                            }
                            else
                            {
                                img.Save(ouputStream, System.Drawing.Imaging.ImageFormat.Png);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (source != null)
                {
                    source.Dispose();
                }
                if (gdiobj != null)
                {
                    gdiobj.Dispose();
                }
            }
        }
Ejemplo n.º 10
0
        public static string extractImagefromPdf(string pdfSource)
        {
            //var pdfsource = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\marksheet.pdf-mysigned";
            PdfReader pdf = new PdfReader(pdfSource);
            RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(pdfSource);

            try
            {
                PdfDictionary pd   = pdf.GetPageN(1);
                PdfDictionary res  = (PdfDictionary)PdfReader.GetPdfObject(pd.Get(PdfName.RESOURCES));
                PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
                if (xobj != null)
                {
                    foreach (PdfName name in xobj.Keys)
                    {
                        PdfObject obj = xobj.Get(name);
                        if (obj.IsIndirect())
                        {
                            PdfDictionary tg   = (PdfDictionary)PdfReader.GetPdfObject(obj);
                            PdfName       type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
                            if (PdfName.IMAGE.Equals(type))
                            {
                                int       XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                PdfObject pdfObj    = pdf.GetPdfObject(XrefIndex);
                                PdfStream pdfStrem  = (PdfStream)pdfObj;
                                byte[]    bytes     = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                                if ((bytes != null))
                                {
                                    using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                                    {
                                        memStream.Position = 0;
                                        System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                        var outputPath           = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\";
                                        if (!Directory.Exists(outputPath))
                                        {
                                            Directory.CreateDirectory(outputPath);
                                        }
                                        string path = Path.Combine(outputPath, String.Format(@"{0}.bmp", 1));
                                        System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                                        parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                        System.Drawing.Imaging.ImageCodecInfo jpegEncoder = GetImageEncoder("BMP");
                                        img.Save(path, jpegEncoder, parms);
                                    }
                                }
                            }
                        }
                    }
                }
                return("completed");
            }
            catch (Exception e)
            {
                return(e.Message.ToString());
            }
            finally
            {
                pdf.Close();
            }
        }
Ejemplo n.º 11
0
 public Form1()
 {
     InitializeComponent();
     connected=false;
     encoderParams=new EncoderParameters();
     encoderParams.Param[0]=new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,95L);
     jpegCodec=ImageCodecInfo.GetImageEncoders().First(codec=>codec.MimeType=="image/jpeg");
 }
Ejemplo n.º 12
0
		public void Save(FileStream fileStream, ImageCodecInfo encoder, int quality)
		{
			var encoderParams = new EncoderParameters(2);
			encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);			
			encoderParams.Param[1] = new EncoderParameter(Encoder.ColorDepth, 24L);				
			_bitmap.Save(fileStream, encoder, encoderParams);
			fileStream.Close();
		}
 public LzwCompression(int Quality)
 {
     this.parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Quality);
     this.encoderInfo = GetEncoderInfo("image/jpeg");
     this.encoderParams = new EncoderParameters(2);
     this.encoderParams.Param[0] = parameter;
     this.encoderParams.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)2);
 }
Ejemplo n.º 14
0
 public JpgCompression(long quality)
 {
     EncoderParameter parameter = new EncoderParameter(Encoder.Quality, quality);
     this._encoderInfo = GetEncoderInfo("image/jpeg");
     this._encoderParams = new EncoderParameters(2);
     this._encoderParams.Param[0] = parameter;
     this._encoderParams.Param[1] = new EncoderParameter(Encoder.Compression, (long) EncoderValue.CompressionRle);
 }
Ejemplo n.º 15
0
 public static void Save(this Bitmap image, Stream rstream, string mimeType = "image/png")
 {
     System.Drawing.Imaging.ImageCodecInfo    codec   = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().First(f => f.MimeType == mimeType);
     System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
     eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
     image.Save(rstream, codec, eParams);
     rstream.Seek(0, SeekOrigin.Begin);
 }
Ejemplo n.º 16
0
 public ScreenCapture(long jpgquality = 60L)
 {
     _jgpEncoder = GetEncoder(ImageFormat.Jpeg);
     var myEncoder = System.Drawing.Imaging.Encoder.Quality;
     var myEncoderParameter = new EncoderParameter(myEncoder, jpgquality);
     _myEncoderParameters = new EncoderParameters(1);
     _myEncoderParameters.Param[0] = myEncoderParameter;
 }
Ejemplo n.º 17
0
        //--
        //-- save bitmap object to JPEG of specified quality level
        //--
        private static void BitmapToJPEG(Bitmap objBitmap, string strFilename, long lngCompression = 75)
        {
            System.Drawing.Imaging.EncoderParameters objEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            System.Drawing.Imaging.ImageCodecInfo    objImageCodecInfo    = GetEncoderInfo("image/jpeg");

            objEncoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, lngCompression);
            objBitmap.Save(strFilename, objImageCodecInfo, objEncoderParameters);
        }
Ejemplo n.º 18
0
        public static void CompressImage(string fullFilePath, string destinationPath, long compression)
        {
            Bitmap bitmap = GetBitmap(fullFilePath);

            if (bitmap == null)
            {
                return;
            }

            Bitmap newImage = new Bitmap(bitmap);

            bool encoderFound = false;

            System.Drawing.Imaging.ImageCodecInfo encoder = null;

            var fileName = Path.GetFileName(fullFilePath);

            if (fileName.ToLower().EndsWith(".jpg") || fileName.ToLower().EndsWith(".jpeg"))
            {
                encoderFound = true;
                encoder      = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else if (fileName.ToLower().EndsWith(".bmp"))
            {
                encoderFound = true;
                encoder      = GetEncoder(System.Drawing.Imaging.ImageFormat.Bmp);
            }
            else if (fileName.ToLower().EndsWith(".tiff"))
            {
                encoderFound = true;
                encoder      = GetEncoder(System.Drawing.Imaging.ImageFormat.Tiff);
            }
            else if (fileName.ToLower().EndsWith(".gif"))
            {
                encoderFound = true;
                encoder      = GetEncoder(System.Drawing.Imaging.ImageFormat.Gif);
            }
            else if (fileName.ToLower().EndsWith(".png"))
            {
                encoderFound = true;
                encoder      = GetEncoder(System.Drawing.Imaging.ImageFormat.Png);
            }

            if (encoderFound)
            {
                System.Drawing.Imaging.Encoder           myEncoder           = System.Drawing.Imaging.Encoder.Quality;
                System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
                System.Drawing.Imaging.EncoderParameter  myEncoderParameter  = new System.Drawing.Imaging.EncoderParameter(myEncoder, compression);
                myEncoderParameters.Param[0] = myEncoderParameter;

                newImage.Save(System.IO.Path.Combine(destinationPath), encoder, myEncoderParameters);
            }
            else
            {
                newImage.Save(System.IO.Path.Combine(destinationPath));
            }
        }
Ejemplo n.º 19
0
 public GetMapResponse(Image image, ImageCodecInfo codecInfo)
 {
     if (image == null)
         throw new ArgumentNullException("image");
     if (codecInfo == null)
         throw new ArgumentNullException("codecInfo");
     _image = image;
     _codecInfo = codecInfo;
 }
Ejemplo n.º 20
0
 public MJPEGStream()
 {
     Jpeginfo = GetJpegInfo();
     Quality = 70;
     HeadArray = ServerCoding.GetBytes(MJPEGHead);
     MJPEGLastArray = ServerCoding.GetBytes(MJPEGLast);
     JPEGHeadArray = ServerCoding.GetBytes(JPEGHead);
     isRun = false;
 }
Ejemplo n.º 21
0
        override internal void Run(IPresent ip, Row row)
        {
            Report rpt = ip.Report();

            ICustomReportItem cri = null;

            try
            {
                cri = RdlEngineConfig.CreateCustomReportItem(_Type);
                Type   a  = cri.GetType();
                Bitmap bm = null;
                SetProperties(rpt, row, cri);
                int width = WidthCalc(rpt, null) -
                            (Style == null ? 0 :
                             (Style.EvalPaddingLeftPx(rpt, row) + Style.EvalPaddingRightPx(rpt, row)));
                int height = RSize.PixelsFromPoints(this.HeightOrOwnerHeight) -
                             (Style == null ? 0 :
                              (Style.EvalPaddingTopPx(rpt, row) + Style.EvalPaddingBottomPx(rpt, row)));
                bm = new Bitmap(width, height);
                cri.DrawImage(ref bm);

                MemoryStream ostrm = new MemoryStream();
                // 06122007AJM Changed to use high quality JPEG encoding
                //bm.Save(ostrm, IMAGEFORMAT);	// generate a jpeg   TODO: get png to work with pdf
                System.Drawing.Imaging.ImageCodecInfo[] info;
                info = ImageCodecInfo.GetImageEncoders();
                EncoderParameters encoderParameters;
                encoderParameters = new EncoderParameters(1);
                // 20022008 AJM GJL - Using centralised image quality
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.CustomImageQuality);
                System.Drawing.Imaging.ImageCodecInfo codec = null;
                for (int i = 0; i < info.Length; i++)
                {
                    if (info[i].FormatDescription == "JPEG")
                    {
                        codec = info[i];
                        break;
                    }
                }
                bm.Save(ostrm, codec, encoderParameters);

                ip.Image(new Image(rpt.ReportDefinition, this, xNode), row, null, ostrm);
                ostrm.Close();
            }
            catch (Exception ex)
            {
                rpt.rl.LogError(8, string.Format("Exception in CustomReportItem handling.\n{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                if (cri != null)
                {
                    cri.Dispose();
                }
            }
            return;
        }
Ejemplo n.º 22
0
 static DevicePresenter()
 {
     ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
     for (int j = 0; j < encoders.Length; ++j)
     {
         if (encoders[j].MimeType == "image/jpeg")
             _codecInfo = encoders[j];
     }
 }
Ejemplo n.º 23
0
        //public string pdfToPic(string sourcePdf, string outputPath)
        public static bool pdfToPic(string pdfInputPath, string outputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat)
        {
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(pdfInputPath);
            RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(pdfInputPath);
            bool flag = true;

            try
            {
                for (int pageNumber = startPageNum; pageNumber <= endPageNum; pageNumber++)
                {
                    PdfDictionary pg = pdf.GetPageN(pageNumber);

                    // recursively search pages, forms and groups for images.
                    PdfObject obj = FindImageInPDFDictionary(pg);
                    if (obj != null)
                    {
                        int       XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        PdfObject pdfObj    = pdf.GetPdfObject(XrefIndex);
                        PdfStream pdfStrem  = (PdfStream)pdfObj;
                        byte[]    bytes     = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                        if ((bytes != null))
                        {
                            using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                            {
                                memStream.Position = 0;
                                System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                // must save the file while stream is open.


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

                                //path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber));
                                System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                                parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                System.Drawing.Imaging.ImageCodecInfo jpegEncoder = GetImageEncoder("JPEG");
                                img.Save(outputPath + imageName + "." + imageFormat.ToString(), jpegEncoder, parms);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                flag = false;
            }
            finally
            {
                pdf.Close();
                raf.Close();
            }
            return(flag);
        }
Ejemplo n.º 24
0
 //int ImageWidth = -1;
 //int ImageHeight = -1;
 public MJPEGStream(int Port)
 {
     Jpeginfo = GetJpegInfo();
     Quality = 70;
     myList = new TcpListener(IPAddress.Any, Port);
     HeadArray = ServerCoding.GetBytes(MJPEGHead);
     MJPEGLastArray = ServerCoding.GetBytes(MJPEGLast);
     JPEGHeadArray = ServerCoding.GetBytes(JPEGHead);
     isRun = false;
 }
Ejemplo n.º 25
0
		public static ImageCodecInfo[] GetImageDecoders () 
		{
			Hashtable oldInfo = ImageCodec.Decoders;
			ImageCodecInfo [] newInfo = new ImageCodecInfo [oldInfo.Count];
			int i=0;
			foreach (ImageCodecInfo codec in oldInfo.Values) {
				newInfo [i++] = (ImageCodecInfo) codec.MemberwiseClone ();
			}
			return newInfo;
		}
        public string Resize(Bitmap bmp, string strFileThumb, int P_Width)
        {
            string thumbnailFilePath = string.Empty;
            string FileName          = string.Empty;

            try
            {
                float ratio     = (float)bmp.Width / bmp.Height;
                int   imgHeight = 0;
                //System.Drawing.Image img = Crop(bmp, P_Width, (int)(P_Width * ratio), AnchorPosition.Center);
                // int iz = HttpContext.Current.Request.QueryString["iz"] != null ? Convert.ToInt32(HttpContext.Current.Request.QueryString["iz"]) : 0;
                //switch (iz)
                {
                    //case 0 :
                    //    //3x4
                    //    imgHeight = Convert.ToInt32( 0.75 * P_Width);
                    //    break;
                    //case 1:
                    //    //16x9
                    //    imgHeight = Convert.ToInt32((float)9 / 16 * P_Width);
                    //    break;
                    // default:
                    // normal:
                    imgHeight = Convert.ToInt32(P_Width / ratio);
                    //  break;
                }

                imgHeight = Convert.ToInt32((float)9 / 16 * P_Width);

                System.Drawing.Image img = Crop(bmp, P_Width + 1, imgHeight + 1, AnchorPosition.Center);
                using (Bitmap thumb = new Bitmap(img))
                {
                    //thumb.SetResolution(P_Width, P_Width);
                    using (Graphics g = Graphics.FromImage(thumb)) // Create Graphics object from original Image
                    {
                        g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.High;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        //Set Image codec of JPEG type, the index of JPEG codec is "1"
                        System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
                        //Set the parameters for defining the quality of the thumbnail... here it is set to 100%
                        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
                        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 92L);
                        //Now draw the image on the instance of thumbnail Bitmap object
                        g.DrawImage(thumb, new Rectangle(0, 0, thumb.Width, thumb.Height));
                        thumb.Save(strFileThumb, codec, eParams);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(FileName);
        }
Ejemplo n.º 27
0
		public static void SaveImage(Image image, string fileName, ImageCodecInfo jpgEncoder, EncoderParameters parameters)
		{
			RetryUtility.Retry(() => image.Save(fileName, jpgEncoder, parameters),
				RetryUtility.kDefaultMaxRetryAttempts,
				RetryUtility.kDefaultRetryDelay,
				new HashSet<Type>
				{
					Type.GetType("System.IO.IOException"),
					Type.GetType("System.Runtime.InteropServices.ExternalException")
				});
		}
Ejemplo n.º 28
0
 static AvatarBuilder()
 {
     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
     foreach (ImageCodecInfo codec in codecs)
     {
         if (codec.FormatID == ImageFormat.Jpeg.Guid)
         {
             jpegImageCodeInfo = codec;
         }
     }
 }
Ejemplo n.º 29
0
        public static void ExtractImagesFromPDF(string sourcePdf, string outputPath)
        {
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(sourcePdf);

            //RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);

            try
            {
                for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
                {
                    PdfDictionary pg = pdf.GetPageN(pageNumber);

                    // recursively search pages, forms and groups for images.
                    PdfObject obj = FindImageInPDFDictionary(pg);
                    if (obj != null)
                    {
                        int       XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        PdfObject pdfObj    = pdf.GetPdfObject(XrefIndex);
                        PdfStream pdfStrem  = (PdfStream)pdfObj;
                        byte[]    bytes     = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                        if ((bytes != null))
                        {
                            using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                            {
                                memStream.Position = 0;
                                System.Drawing.Image img = ImageHelper.ResizeImage(System.Drawing.Image.FromStream(memStream), .33M);
                                // must save the file while stream is open.
                                if (!Directory.Exists(outputPath))
                                {
                                    Directory.CreateDirectory(outputPath);
                                }

                                string path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber));
                                System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
                                parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                var encoders = ImageCodecInfo.GetImageEncoders();
                                System.Drawing.Imaging.ImageCodecInfo jpegEncoder = encoders.FirstOrDefault(p => p.CodecName == "Built-in JPEG Codec");
                                img.Save(path, jpegEncoder, parms);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                pdf.Close();
                //raf.Close();
            }
        }
 public JanelaTreinarDetector()
 {
     InitializeComponent();
     CvInvoke.UseOpenCL = false;
     //Parent = _Parent;
     //Face = Parent.Face;
     Face = new CascadeClassifier("haarcascade_frontalface_default.xml");//Our face detection method 
   
     ENC_Parameters.Param[0] = ENC;
     Image_Encoder_JPG = GetEncoder(ImageFormat.Jpeg);
     initialise_capture();
 }
Ejemplo n.º 31
0
 static ControllerHelpers()
 {
     _MaxWidth = int.Parse(ConfigurationManager.AppSettings["UploadFileMaxWidth"]);
     _ThumbMaxWidth = int.Parse(ConfigurationManager.AppSettings["ThumbFileMaxWidth"]);
     _UserImgFolder = ConfigurationManager.AppSettings["UserImageFolder"];
     _JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Where(codec => codec.MimeType == "image/jpeg").First();
     var qualityEncoder = Encoder.Quality;
     var quality = 100;
     var ratio = new EncoderParameter(qualityEncoder, quality);
     _EncoderParameters = new EncoderParameters(1);
     _EncoderParameters.Param[0] = ratio;
 }
Ejemplo n.º 32
0
		public EngineGarmin ()
		{
			_jpegCodec = GetEncoderInfo("image/jpeg");

			// Is there a jpeg encoder?
			// Jpeg image codec
			if (_jpegCodec == null)
				throw new InvalidOperationException("No JPEG encoder found");

			_encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24L);
			_encParams.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
		}
Ejemplo n.º 33
0
        private static string ConvertJpgToPng(int i, ImageRenderListener listener, string diretorio)
        {
            System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
            parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);

            System.Drawing.Imaging.ImageCodecInfo jpegEncoder = ImageCodecInfo.GetImageEncoders().Single(p => p.CodecName.Contains("PNG"));
            System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(listener.Images[i]));
            string path = diretorio + "\\" + i + listener.ImageNames[i].ToLower().Replace(".jpg", ".png");

            img.Save(path, jpegEncoder, parms);
            return(path);
        }
Ejemplo n.º 34
0
        /// <summary>Saves image to a file</summary>
        /// <param name="bmp">Bitmap to save</param>
        /// <param name="FileName">File name</param>
        /// <param name="Quality">Image quality, from 0 to 100. 97 should do fine</param>
        public static void Save(Bitmap bmp, string FileName, int Quality)
        {
            Int64 quality = (Int64)Quality;

            System.Drawing.Imaging.Encoder           Encoder             = System.Drawing.Imaging.Encoder.Quality;
            System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            System.Drawing.Imaging.EncoderParameter  myEncoderParameter  = new System.Drawing.Imaging.EncoderParameter(Encoder, quality);
            myEncoderParameters.Param[0] = myEncoderParameter;
            System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);

            bmp.Save(FileName, jgpEncoder, myEncoderParameters);
        }
Ejemplo n.º 35
0
 /// <summary>
 /// 质量控制
 /// </summary>
 /// <param name="level">级别,1-100</param>
 /// <param name="mimeType">图片格式,</param>
 private static void setQuality(int level, string mimeType)
 {
     var codecs = ImageCodecInfo.GetImageEncoders();
     ici = null;
     foreach (var codec in codecs)
     {
         if (codec.MimeType == "image/" + mimeType)
             ici = codec;
     }
     ep = new EncoderParameters();
     ep.Param[0] = new EncoderParameter(Encoder.Quality, level);
 }
		static void Check (ImageCodecInfo e, ImageCodecInfo d, Guid FormatID, string CodecName, string DllName,
			string FilenameExtension, ImageCodecFlags Flags, string FormatDescription,
			string MimeType, int Version, int signatureLength, string mask, string pattern, string pattern2)
		{
			Regex extRegex = new Regex (@"^(\*\.\w+(;(\*\.\w+))*;)?"+
				Regex.Escape (FilenameExtension)+@"(;\*\.\w+(;(\*\.\w+))*)?$",
				RegexOptions.IgnoreCase | RegexOptions.Singleline);

			if (e != null) {
				Assert.AreEqual (FormatID, e.FormatID, "Encoder.FormatID");
				Assert.IsTrue (e.CodecName.IndexOf (CodecName)>=0,
					"Encoder.CodecName contains "+CodecName);
				Assert.AreEqual (DllName, e.DllName, "Encoder.DllName");
				Assert.IsTrue (extRegex.IsMatch (e.FilenameExtension),
					"Encoder.FilenameExtension is a right list with "+FilenameExtension);
				Assert.AreEqual (Flags, e.Flags, "Encoder.Flags");
				Assert.IsTrue (e.FormatDescription.IndexOf (FormatDescription)>=0,
					"Encoder.FormatDescription contains "+FormatDescription);
				Assert.IsTrue (e.MimeType.IndexOf (MimeType)>=0,
					"Encoder.MimeType contains "+MimeType);

				Assert.AreEqual (signatureLength, e.SignatureMasks.Length, "Encoder.SignatureMasks.Length");
				for (int i = 0; i < signatureLength; i++) {
					Assert.AreEqual (mask, BitConverter.ToString (e.SignatureMasks[i]), String.Format ("Encoder.SignatureMasks[{0}]", i));
				}
				Assert.AreEqual (signatureLength, e.SignaturePatterns.Length, "Encoder.SignaturePatterns.Length");
				Assert.AreEqual (pattern, BitConverter.ToString (e.SignaturePatterns[0]), "Encoder.SignaturePatterns[0]");
				if (pattern2 != null)
					Assert.AreEqual (pattern2, BitConverter.ToString (e.SignaturePatterns[1]), "Encoder.SignaturePatterns[1]");
			}
			if (d != null) {
				Assert.AreEqual (FormatID, d.FormatID, "Decoder.FormatID");
				Assert.IsTrue (d.CodecName.IndexOf (CodecName)>=0,
					"Decoder.CodecName contains "+CodecName);
				Assert.AreEqual (DllName, d.DllName, "Decoder.DllName");
				Assert.IsTrue (extRegex.IsMatch (d.FilenameExtension),
					"Decoder.FilenameExtension is a right list with "+FilenameExtension);
				Assert.AreEqual (Flags, d.Flags, "Decoder.Flags");
				Assert.IsTrue (d.FormatDescription.IndexOf (FormatDescription)>=0,
					"Decoder.FormatDescription contains "+FormatDescription);
				Assert.IsTrue (d.MimeType.IndexOf (MimeType)>=0,
					"Decoder.MimeType contains "+MimeType);

				Assert.AreEqual (signatureLength, d.SignatureMasks.Length, "Decoder.SignatureMasks.Length");
				for (int i = 0; i < signatureLength; i++) {
					Assert.AreEqual (mask, BitConverter.ToString (d.SignatureMasks[i]), String.Format ("Decoder.SignatureMasks[{0}]", i));
				}
				Assert.AreEqual (signatureLength, d.SignaturePatterns.Length, "Decoder.SignaturePatterns.Length");
				Assert.AreEqual (pattern, BitConverter.ToString (d.SignaturePatterns[0]), "Decoder.SignaturePatterns[0]");
				if (pattern2 != null)
					Assert.AreEqual (pattern2, BitConverter.ToString (d.SignaturePatterns[1]), "Decoder.SignaturePatterns[1]");
			}
		}
Ejemplo n.º 37
0
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="oldpath">原图片绝对地址</param>
        /// <param name="newpath">新图片放置的绝对地址</param>
        public void addWaterMark(string oldpath, string newpath)
        {
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);
                Bitmap   b = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(b);
                g.Clear(Color.White);
                g.SmoothingMode     = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.High;

                g.DrawImage(image, 0, 0, image.Width, image.Height);

                if (IsWaterMark)
                {
                    switch (this.WMType)
                    {
                    case WaterMarkType.WM_IMAGE:     //水印图片
                        this.addWatermarkImage(g, _waterMarkImgPath, WMLocation, image.Width, image.Height);
                        break;

                    case WaterMarkType.WM_TEXT:    //水印文字
                        this.addWatermarkText(g, this.WaterMarkText, WMLocation, image.Width, image.Height);
                        break;
                    }

                    #region 降低图片质量
                    System.Drawing.Imaging.ImageCodecInfo    encoder       = GetEncoderInfo("image/jpeg");
                    System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
                    encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)80);
                    #endregion
                    b.Save(newpath, encoder, encoderParams);
                    encoderParams.Dispose();
                    b.Dispose();
                    image.Dispose();
                }
            }
            catch
            {
                if (File.Exists(oldpath))
                {
                    File.Delete(oldpath);
                }
            }
            finally
            {
                if (File.Exists(oldpath))
                {
                    File.Delete(oldpath);
                }
            }
        }
Ejemplo n.º 38
0
    public static bool ImgResize(string Path, int Width, int Height, System.IO.Stream StreamFileupload, long ImgQuality)
    {
        try
        {
            //Thumbnain yaradaq, şəkil təmizliyi maksimum olacaq. ***************************
            string thumbnailFilePath = string.Empty;
            using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(StreamFileupload))
            {
                if (Width == -1)
                {
                    Width = (bmp.Width * (Height * 100) / bmp.Height) / 100;
                }
                else if (Height == -1)
                {
                    Height = (bmp.Height * (Width * 100) / bmp.Width) / 100;
                }

                thumbnailFilePath = HttpContext.Current.Server.MapPath(Path);         //Save File
                System.Drawing.Size newSize = new System.Drawing.Size(Width, Height); // Thumbnail ölçüsü (width = xxx) (height = xxx)

                using (System.Drawing.Bitmap thumb = new System.Drawing.Bitmap(bmp, newSize))
                {
                    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumb)) // Original şəkili grafikə çeviririk: Təmizləmək üçün
                    {
                        //Təmizlik paramterləri:
                        g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.High;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                        //Şəkil Codec yaradırıq. Sondakı 1 index dəyəridir.
                        System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];

                        //Encoding paramter maksimum 100L gedir o zaman şəkilin həcmi çox olur.
                        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);

                        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImgQuality);

                        //Şəkili yaradırıq və dəyərlərini üstəki kimi daxil edirik.
                        g.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, thumb.Width, thumb.Height));
                        //Son olaraq Save edirik:
                        thumb.Save(thumbnailFilePath, codec, eParams);
                        return(true);
                    }
                }
            }
        }
        catch (Exception er)
        {
            DALCL.ErrorLog(string.Format("ImgResize catch error: {0}, path: {1}", er.Message, Path));
            return(false);
        }
    }
Ejemplo n.º 39
0
        static ScanImg()
        {
            quality = new EncoderParameter(Encoder.Quality, 50L);

              ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
              for (int i = 0; i < codecs.Length; i++) {
            if (codecs[i].MimeType == "image/jpeg") {
              jpeg = codecs[i];
              break;
            } else
              jpeg = null;
              }
        }
Ejemplo n.º 40
0
        public ImageCodecAdapter(ImageCodecInfo codec)
        {
            this.codec = codec;
            this.parameters = new EncoderParameters {
                Param = new[] { new EncoderParameter(Encoder.Quality, 100L) }
            };

            this.FileExtensions = codec.FilenameExtension.Split(';')
                                                         .Select(e => e.TrimStart('*', '.').ToLowerInvariant())
                                                         .ToArray()
                                                         .AsReadOnly();
            this.MediaTypeNames = new[] { codec.MimeType }.AsReadOnly();
        }
Ejemplo n.º 41
0
        private void ConfigureImageQuality()
        {
            const long JPEGQUALITY = 20; // 1-100 or 0 for default

            myImageCodecInfo = GetEncoderInfo("image/jpeg");

            if (JPEGQUALITY != 0)
            {
                // If not using the default jpeg quality setting
                EncoderParameter myEncoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, JPEGQUALITY);
                myEncoderParameters = new EncoderParameters(1);
                myEncoderParameters.Param[0] = myEncoderParameter;
            }
        }
Ejemplo n.º 42
0
        public JpegFileHandler(
            string _outputFolder,
            long _jpegQuality = 85L,
            List<IImageHandler> _postHandlers = null )
        {
            m_OutputFolder = _outputFolder;
            m_PostImageHandlers = _postHandlers;

            //Prepare image processing
            m_ImageCodec = GetEncoderInfo(ImageFormat.Jpeg);
            var encoderQuality = Encoder.Quality;
            var myEncoderParameter = new EncoderParameter(encoderQuality, _jpegQuality);
            m_EncoderParameters = new EncoderParameters(1);
            m_EncoderParameters.Param[0] = myEncoderParameter;
        }
Ejemplo n.º 43
0
 private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(string mimeType)
 {
     //根据 mime 类型,返回编码器
     System.Drawing.Imaging.ImageCodecInfo   result   = null;
     System.Drawing.Imaging.ImageCodecInfo[] encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
     for (int i = 0; i < encoders.Length; i++)
     {
         if (encoders[i].MimeType == mimeType)
         {
             result = encoders[i];
             break;
         }
     }
     return(result);
 }
        public static void BitmapSaveJpegQuality(Bitmap srcImage, string sDest, int nQual) //Dustin Getz, stackoverflow 1484759
        {
            if (nQual < 0 || nQual > 100) throw new Exception("invalid quality specified");
            if (s_jpgEncoder == null)
            {
                s_jpgEncoder = GetEncoder(ImageFormat.Jpeg);
                if (s_jpgEncoder == null) throw new Exception("jpgEncoder not found");
            }
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1); //array of EncoderParameter objs

            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, nQual);
            myEncoderParameters.Param[0] = myEncoderParameter;
            srcImage.Save(sDest, s_jpgEncoder, myEncoderParameters);
        }
Ejemplo n.º 45
0
    public void Boyutlandir(System.Drawing.Image orjinalFoto, int Genislik, int Yukseklik, string KlasorYolu, string dosyaAdi)
    {
        System.Drawing.Bitmap islenmisFotograf = null;

        System.Drawing.Graphics grafik = null;

        int hedefGenislik = Genislik;

        int hedefYukseklik = Yukseklik;

        int new_width, new_height;

        new_height = (int)Math.Round(((float)orjinalFoto.Height * (float)Genislik) / (float)orjinalFoto.Width);

        new_width = hedefGenislik;

        hedefYukseklik = new_height;

        new_width = new_width > hedefGenislik ? hedefGenislik : new_width;

        new_height = new_height > hedefYukseklik ? hedefYukseklik : new_height;

        islenmisFotograf = new System.Drawing.Bitmap(hedefGenislik, hedefYukseklik);

        grafik = System.Drawing.Graphics.FromImage(islenmisFotograf);

        grafik.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, hedefGenislik, hedefYukseklik));

        int paste_x = (hedefGenislik - new_width) / 2;

        int paste_y = (hedefYukseklik - new_height) / 2;

        grafik.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        grafik.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

        grafik.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

        System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];

        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);

        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L);

        grafik.DrawImage(orjinalFoto, paste_x, paste_y, new_width, new_height);

        islenmisFotograf.Save(HttpContext.Current.Server.MapPath("~/" + KlasorYolu + "kucuk_" + dosyaAdi), codec, eParams);
    }
Ejemplo n.º 46
0
        public void Save(System.IO.Stream stream, Imaging.ImageCodecInfo info, Imaging.EncoderParameters e)
        {
            Android.Graphics.Bitmap.CompressFormat _format;
            switch (info.FormatDescription)
            {
            case "PNG":
                _format = Android.Graphics.Bitmap.CompressFormat.Png;
                break;

            case "JPEG":
            default:
                _format = Android.Graphics.Bitmap.CompressFormat.Jpeg;
                break;
            }
            ABitmap.Compress(_format, 100, stream);
        }
Ejemplo n.º 47
0
        public NetworkManager(Guid applicationGuid, MainWindow mwObject)
        {
            serverSocket = new BluetoothListener(applicationGuid);
              serverSocket.Start();

              jpgEncoder = GetEncoder(ImageFormat.Jpeg);
              myEncoderParameters = new EncoderParameters(1);
              EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, Settings.Default.CompressionLevel);
              myEncoderParameters.Param[0] = myEncoderParameter;

              serverWorker = new BackgroundWorker();
              serverWorker.DoWork += new DoWorkEventHandler(ServerWorker_DoWork);
              serverWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ServerWorker_RunWorkerCompleted);

              this.mwObject = mwObject;
        }
Ejemplo n.º 48
0
        //根据 mime 类型,返回编码器
        private System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            System.Drawing.Imaging.ImageCodecInfo result = null;

            //检索已安装的图像编码解码器的相关信息。
            System.Drawing.Imaging.ImageCodecInfo[] encoders =
                System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < encoders.Length; i++)
            {
                if (encoders[i].MimeType == mimeType)
                {
                    result = encoders[i];
                    break;
                }
            }
            return(result);
        }
Ejemplo n.º 49
0
        public void MergeTiffPages(string str_DestinationPath, string[] sourceFiles)
        {
            System.Drawing.Imaging.ImageCodecInfo codec = null;

            foreach (System.Drawing.Imaging.ImageCodecInfo cCodec in System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders())
            {
                if (cCodec.CodecName == "Built-in TIFF Codec")
                {
                    codec = cCodec;
                }
            }

            try
            {
                System.Drawing.Imaging.EncoderParameters imagePararms = new System.Drawing.Imaging.EncoderParameters(1);
                imagePararms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.MultiFrame);

                if (sourceFiles.Length == 1)
                {
                    System.IO.File.Copy((string)sourceFiles[0], str_DestinationPath, true);
                }
                else if (sourceFiles.Length >= 1)
                {
                    System.Drawing.Image DestinationImage = (System.Drawing.Image)(new System.Drawing.Bitmap((string)System.Configuration.ConfigurationSettings.AppSettings["Path"] + sourceFiles[0]));

                    DestinationImage.Save(str_DestinationPath, codec, imagePararms);

                    imagePararms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.FrameDimensionPage);

                    for (int i = 0; i < sourceFiles.Length - 1; i++)
                    {
                        System.Drawing.Image img = (System.Drawing.Image)(new System.Drawing.Bitmap((string)sourceFiles[i]));

                        DestinationImage.SaveAdd(img, imagePararms);
                        img.Dispose();
                    }

                    imagePararms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.Flush);
                    DestinationImage.SaveAdd(imagePararms);
                    imagePararms.Dispose();
                    DestinationImage.Dispose();
                }
            }
            catch (Exception ex)
            { }
        }
        public ScreenCaptureWriter()
        {
            var codecs = ImageCodecInfo.GetImageDecoders();
            foreach (var imageCodecInfo in codecs)
            {
                if (imageCodecInfo.FormatID == ImageFormat.Jpeg.Guid)
                {
                    _imageCodecInfo = imageCodecInfo;
                    break;
                }
            }

            _encoder = Encoder.Quality;
            _encoderParams = new EncoderParameters(1);
            var qualityParam = new EncoderParameter(_encoder, 100L);
            _encoderParams.Param[0] = qualityParam;
        }
Ejemplo n.º 51
0
 public static void CreateThumbnail(string sourceFilename, string destFilename, int width, int height)
 {
     System.Drawing.Image image = System.Drawing.Image.FromFile(sourceFilename);
     if (image.Width <= width && image.Height <= height)
     {
         System.IO.File.Copy(sourceFilename, destFilename, true);
         image.Dispose();
     }
     else
     {
         int   width2  = image.Width;
         int   height2 = image.Height;
         float num     = (float)height / (float)height2;
         if ((float)width / (float)width2 < num)
         {
             num = (float)width / (float)width2;
         }
         width  = (int)((float)width2 * num);
         height = (int)((float)height2 * num);
         System.Drawing.Image    image2   = new System.Drawing.Bitmap(width, height);
         System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(image2);
         graphics.Clear(System.Drawing.Color.White);
         graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
         graphics.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
         graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, width2, height2), System.Drawing.GraphicsUnit.Pixel);
         System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters();
         System.Drawing.Imaging.EncoderParameter  encoderParameter  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
         encoderParameters.Param[0] = encoderParameter;
         System.Drawing.Imaging.ImageCodecInfo[] imageEncoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
         System.Drawing.Imaging.ImageCodecInfo   encoder       = null;
         for (int i = 0; i < imageEncoders.Length; i++)
         {
             if (imageEncoders[i].FormatDescription.Equals("JPEG"))
             {
                 encoder = imageEncoders[i];
                 break;
             }
         }
         image2.Save(destFilename, encoder, encoderParameters);
         encoderParameters.Dispose();
         encoderParameter.Dispose();
         image.Dispose();
         image2.Dispose();
         graphics.Dispose();
     }
 }
        public byte[] CompressBmpToJPEGArray(long CompressionRate, Bitmap aBitmap)
        {
            byte[] byteArray = new byte[0];
            MemoryStream stream = new MemoryStream();

            myImageCodecInfo = GetEncoderInfo("image/jpeg");
            myEncoder = System.Drawing.Imaging.Encoder.Quality;
            myEncoderParameters = new EncoderParameters(1);
            myEncoderParameter = new EncoderParameter(myEncoder, CompressionRate);
            myEncoderParameters.Param[0] = myEncoderParameter;

            aBitmap.Save(stream, myImageCodecInfo, myEncoderParameters);
            stream.Close();
            byteArray = stream.ToArray();

            return byteArray;
        }
Ejemplo n.º 53
0
        public frmQuickUpload()
        {
            Client.form_QuickUpload = this;
            encoder_params_jpg.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L);

            ImageCodecInfo[] images = ImageCodecInfo.GetImageDecoders();

            // Get all the codecs for encoding the images.
            foreach(ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders()) {
                if(codec.MimeType == "image/jpeg") {
                    codec_jpeg = codec;
                }
            }

            InitializeComponent();

            _panDropUpload.Height = 0;
            _panDropUpload.Visible = true;

            // Immediately hide the confirmation row.
            _tlpUploadTable.RowStyles[1].Height = 0;
            _panConfirmUpload.Visible = false;

            // Make the form load the previous saved height if there is any.
            int saved_win_height = Client.config.get<int>("frmquickupload.window.height");
            this.Height = (saved_win_height == 0) ? this.Height : saved_win_height;

            // Make sure the form is the correct size.  Windows XP's form widths are less than 7's.
            OperatingSystemInfo osi = Utilities.getOSInfo();
            if(osi.os.Contains("XP")) {
                Size min_size = new Size() {
                    Height = this.MinimumSize.Height - 8,
                    Width = this.MinimumSize.Width - 8
                };

                Size max_size = new Size() {
                    Height = this.MaximumSize.Height - 8,
                    Width = this.MaximumSize.Width - 8
                };

                this.MinimumSize = min_size;
                this.MaximumSize = max_size;
                this.Size = min_size;
            }
        }
Ejemplo n.º 54
0
        public static void SaveBitmapImg(Bitmap bitmap, string path, long quality)
        {
            //设置 原图片 对象的 EncoderParameters 对象
            EncoderParameters parameters = new EncoderParameters(1);

            parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            System.Drawing.Imaging.ImageCodecInfo   ImgCodeInfo = null;
            System.Drawing.Imaging.ImageCodecInfo[] CodecInfo   = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            foreach (System.Drawing.Imaging.ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == "image/jpeg")
                {
                    ImgCodeInfo = ici;
                }
            }

            bitmap.Save(path, ImgCodeInfo, parameters);
        }
Ejemplo n.º 55
0
        /// <summary>
        /// 产生高清缩略图 固定大小
        /// </summary>
        /// <param name="original_image_file">源文件</param>
        /// <param name="object_width">缩略图宽度</param>
        /// <param name="object_height">缩略图高度</param>
        public static void MakeHighQualityThumbnail(string original_image_file, string output, int object_width, int object_height)
        {
            int    actual_width   = 0;
            int    actual_heigh   = 0;
            string outputfilename = output;                                         //original_image_file + ".jpg";

            System.Drawing.Bitmap original_image = new Bitmap(original_image_file); //读取源文件
            actual_width = original_image.Width;
            actual_heigh = original_image.Height;

            Bitmap img = new Bitmap(object_width, object_height);

            img.SetResolution(108f, 108f);
            Graphics gdiobj = Graphics.FromImage(img);

            gdiobj.CompositingQuality = CompositingQuality.HighQuality;
            gdiobj.SmoothingMode      = SmoothingMode.HighQuality;
            gdiobj.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            gdiobj.PixelOffsetMode    = PixelOffsetMode.HighQuality;

            gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0, object_width, object_height);
            Rectangle destrect = new Rectangle(0, 0, object_width, object_height);

            gdiobj.DrawImage(original_image, destrect, 0, 0, actual_width, actual_heigh, GraphicsUnit.Pixel);

            System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
            ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);

            System.Drawing.Imaging.ImageCodecInfo ici = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[0];

            if (ici != null)
            {
                if (File.Exists(outputfilename))
                {
                    File.Delete(outputfilename);
                }
                img.Save(outputfilename, ici, ep);
            }
            else
            {
                img.Save(outputfilename, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
Ejemplo n.º 56
0
    public static void SavePNG(string path, System.Drawing.Image img, int quality)
    {
        if (quality < 0 || quality > 100)
        {
            throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
        }


        // Encoder parameter for image quality
        System.Drawing.Imaging.EncoderParameter qualityParam =
            new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
        // Jpeg image codec
        System.Drawing.Imaging.ImageCodecInfo jpegCodec = GetEncoderInfo("image/png");

        System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;

        img.Save(path, jpegCodec, encoderParams);
    }
Ejemplo n.º 57
0
        /// <summary>
        /// Resizes any.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="imageSize">Size of the image.</param>
        /// <param name="frameSize">Size of the frame.</param>
        /// <param name="frameColor">Color of the frame.</param>
        /// <returns></returns>
        private Bitmap ResizeAny(Bitmap image, Size imageSize, Size frameSize, Color frameColor)
        {
            if (frameSize == image.Size)
            {
                return(image);
            }
            int       x      = (frameSize.Width - imageSize.Width) / 2;
            int       y      = (frameSize.Height - imageSize.Height) / 2;
            Rectangle rect   = new Rectangle(x, y, imageSize.Width, imageSize.Height);
            Bitmap    bitmap = new Bitmap(image, frameSize);

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.CompositingMode    = CompositingMode.SourceCopy;
                graphics.InterpolationMode  = InterpolationMode.High;
                graphics.Clear(frameColor);
                graphics.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            }
            System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            System.Drawing.Imaging.ImageCodecInfo   jpegICI  = null;
            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[i];
                }
            }
            System.Drawing.Imaging.Encoder           myEncoder           = System.Drawing.Imaging.Encoder.Quality;
            System.Drawing.Imaging.EncoderParameters myEncoderParameters = new EncoderParameters(1);
            System.Drawing.Imaging.EncoderParameter  myEncoderParameter  = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            MemoryStream memoryStream = new MemoryStream();

            bitmap.Save(memoryStream, jpegICI, myEncoderParameters);
            Bitmap bitmap_tmp = new Bitmap(memoryStream);

            return(bitmap_tmp);
        }
Ejemplo n.º 58
0
        private void VaryQualityLevel(string imagePath, string name)
        {
            // Get a bitmap.
            bmp1 = new Bitmap(imagePath);
            System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

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

            EncoderParameters myEncoderParameters = new EncoderParameters(1);

            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);

            myEncoderParameters.Param[0] = myEncoderParameter;
            bmp1.Save(Application.StartupPath + "\\Images\\sm_" + name, jgpEncoder, myEncoderParameters);


            bmp1.Dispose();
        }
Ejemplo n.º 59
0
        /// <summary>Saves a list of bitmaps into a Multipicture File. Not working.</summary>
        /// <param name="FileName">File to save to</param>
        /// <param name="bmps">List of bitmaps to write</param>
        private static void WriteMPF(string FileName, List <Bitmap> bmps)
        {
            if (System.IO.File.Exists(FileName))
            {
                System.IO.File.Delete(FileName);
            }

            System.Drawing.Imaging.Encoder           Encoder             = System.Drawing.Imaging.Encoder.Quality;
            System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            System.Drawing.Imaging.EncoderParameter  myEncoderParameter  = new System.Drawing.Imaging.EncoderParameter(Encoder, 97L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);

            foreach (Bitmap bmp in bmps)
            {
                using (FileStream fstr = new FileStream(FileName, FileMode.Append))
                {
                    bmp.Save(fstr, jgpEncoder, myEncoderParameters);
                    fstr.Close();
                }
            }
        }
    public static void yukle(FileUpload fu, string yer, int Ksize, string dosyaadi)
    {
        System.Drawing.Image orjinalFoto       = null;
        HttpPostedFile       jpeg_image_upload = fu.PostedFile;

        orjinalFoto = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);


        System.Drawing.Bitmap   islenmisFotograf = null;
        System.Drawing.Graphics grafik           = null;

        int hedefGenislik = Ksize;
        int hedefYukseklik = Ksize;
        int new_width, new_height;

        new_height     = (int)Math.Round(((float)orjinalFoto.Height * (float)Ksize) / (float)orjinalFoto.Width);
        new_width      = hedefGenislik;
        hedefYukseklik = new_height;
        new_width      = new_width > hedefGenislik ? hedefGenislik : new_width;
        new_height     = new_height > hedefYukseklik ? hedefYukseklik : new_height;

        islenmisFotograf = new System.Drawing.Bitmap(hedefGenislik, hedefYukseklik);
        grafik           = System.Drawing.Graphics.FromImage(islenmisFotograf);
        grafik.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, hedefGenislik, hedefYukseklik));
        int paste_x = (hedefGenislik - new_width) / 2;
        int paste_y = (hedefYukseklik - new_height) / 2;

        grafik.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        grafik.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        grafik.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.Default;

        System.Drawing.Imaging.ImageCodecInfo    codec   = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L);

        grafik.DrawImage(orjinalFoto, paste_x, paste_y, new_width, new_height);
        islenmisFotograf.Save(HttpContext.Current.Server.MapPath(yer + dosyaadi), codec, eParams);
    }