Ejemplo n.º 1
21
        public static bool CropAndResize(string sourceFilePath, string targetFilePath, int x, int y, int width, int height, int destWidth=0, int destHeight=0 )
        {
            Image img = getImage(sourceFilePath, targetFilePath);

            Image target = ImageCropAndResize(img, x, y, width, height, destWidth, destHeight);
            img.Dispose();

            String extension = System.IO.Path.GetExtension(sourceFilePath).ToLower();

            if (extension != ".png")
            {

                ImageCodecInfo jgpEncoder = ImageTools.GetJpgCodec();
                System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 98L);
                myEncoderParameters.Param[0] = myEncoderParameter;

                target.Save(targetFilePath, jgpEncoder, myEncoderParameters);

            }
            else
            {
                target.Save(targetFilePath, System.Drawing.Imaging.ImageFormat.Png);
            }

            return true;
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            FileSize("noname.jpg");
            var image = new Bitmap("noname.jpg");

            var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            var myEncoder = Encoder.Quality;

            var myEncoderParameters = new EncoderParameters(1);
            var myEncoderParameter = new EncoderParameter(myEncoder, 50L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            image.Save(@"TestPhotoQualityFifty.jpg", jgpEncoder, myEncoderParameters);
            FileSize("TestPhotoQualityFifty.jpg");

            myEncoderParameter = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            image.Save(@"TestPhotoQualityHundred.jpg", jgpEncoder, myEncoderParameters);
            FileSize("TestPhotoQualityHundred.jpg");

            myEncoderParameter = new EncoderParameter(myEncoder, 70L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            image.Save(@"TestPhotoQualityZero.jpg", jgpEncoder, myEncoderParameters);
            FileSize("TestPhotoQualityZero.jpg");

            Console.ReadLine();
        }
Ejemplo n.º 3
0
        public static void CompressImage(Image sourceImage, int imageQuality, string savePath)
        {
            try
            {
                //Create an ImageCodecInfo-object for the codec information
                ImageCodecInfo jpegCodec = null;

                //Set quality factor for compression
                EncoderParameter imageQualitysParameter = new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality, imageQuality);

                //List all avaible codecs (system wide)
                ImageCodecInfo[] alleCodecs = ImageCodecInfo.GetImageEncoders();

                EncoderParameters codecParameter = new EncoderParameters(1);
                codecParameter.Param[0] = imageQualitysParameter;

                //Find and choose JPEG codec
                for (int i = 0; i < alleCodecs.Length; i++)
                {
                    if (alleCodecs[i].MimeType == "image/jpeg")
                    {
                        jpegCodec = alleCodecs[i];
                        break;
                    }
                }

                //Save compressed image
                sourceImage.Save(HttpContext.Current.Server.MapPath(savePath), jpegCodec, codecParameter);
            }
            catch (Exception ex)
            {

            }
        }
Ejemplo n.º 4
0
        //// <summary>
        /// 图片切割函数
        /// </summary>
        /// <param name="sourceFile">原始图片文件</param>
        /// <param name="xNum">在X轴上的切割数量</param>
        /// <param name="yNum">在Y轴上的切割数量</param>
        /// <param name="quality">质量压缩比</param>
        /// <param name="outputFile">输出文件名,不带后缀</param>
        /// <returns>成功返回true,失败则返回false</returns>
        public bool ImageCut(String sourceFile, int xNum, int yNum, long quality, String outputFile)
        {
            try
            {
                long imageQuality = quality;
                Bitmap sourceImage = new Bitmap(sourceFile);
                ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");
                Encoder myEncoder = Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                float xWidth = sourceImage.Width / xNum;
                float yWidth = sourceImage.Height / yNum;
                String outputImage = "";

                for (int countY = 0; countY < yNum; countY++)
                    for (int countX = 0; countX < xNum; countX++)
                    {

                        RectangleF cloneRect = new RectangleF(countX * xWidth, countY * yWidth, xWidth, yWidth);
                        Bitmap newImage = sourceImage.Clone(cloneRect, PixelFormat.Format24bppRgb);
                        outputImage = outputFile + countX + countY + ".jpg";
                        newImage.Save(outputImage, myImageCodecInfo, myEncoderParameters);

                    }
                return true;
            }
            catch
            {
                return false;
            }

        }
Ejemplo n.º 5
0
        //http://social.msdn.microsoft.com/forums/en-US/wpf/thread/0f037b9c-779d-45ad-b797-01c25999491b
        public static BitmapImage ImageFromGDIPlus(byte[] bytes)
        {
            var guid = Guid.NewGuid();
            if (Directory.Exists(@"C:\Temp\") == false)
                Directory.CreateDirectory(@"C:\Temp\");

            var stream = new MemoryStream(bytes);
            var badMetadataImage = new Bitmap(stream);
            ImageCodecInfo myImageCodecInfo;
            Encoder myEncoder;
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;
            // get an ImageCodecInfo object that represents the JPEG codec
            myImageCodecInfo = GetEncoderInfo("image/jpeg");
            // 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);
            // Save the image as a JPEG file with quality level 75.
            myEncoderParameter = new EncoderParameter(myEncoder, 75L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            badMetadataImage.Save(@"C:\Temp\" + guid + ".bmp", myImageCodecInfo, myEncoderParameters);
            // Create the source to use as the tb source
            var bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri(@"C:\Temp\" + guid + ".bmp", UriKind.Absolute);
            bi.EndInit();
            return bi;
        }
Ejemplo n.º 6
0
        public static bool KiSaveAsJPEG(Bitmap bmp, string FileName, int Qty)
        {
            try
            {
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);

                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
                ps.Param[0] = p;
                try
                {
                    File.Delete(FileName);
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                }
                bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);

                return true;
            }
            catch
            {
                return false;
            }
        }
Ejemplo n.º 7
0
        /*
         *  使用例子:
         *  ImageCodecInfo jgpEncoder = PaintTools.GetEncoderByFormat(ImageFormat.Jpeg);
         *  EncoderParameters encoderParameters = PaintTools.GetEncoderParametersByNumber(100);
         *  bitMapCut.Save(AppDomain.CurrentDomain.BaseDirectory + savePicPath + "_.jpg", jgpEncoder, encoderParameters);
         */

        /// <summary>
        /// 设置图片品质
        /// </summary>
        /// <param name="compressionRate">100是最好品质</param>
        /// <returns></returns>
        public static EncoderParameters GetEncoderParametersByNumber(int compressionRate = 100)
        {
            System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            System.Drawing.Imaging.EncoderParameter  encoderParameter  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compressionRate);//这里设品质
            encoderParameters.Param[0] = encoderParameter;
            return(encoderParameters);
        }
Ejemplo n.º 8
0
        public static void work() {
            keepGoing = true;
           
            Task.Factory.StartNew(()=>check());
            do {
                Bitmap img = GetScreenShot();
                ImageCodecInfo[] codec = ImageCodecInfo.GetImageEncoders();

                // initialisation d'un tableau de dimension 2 de parametres d'encodages 
                EncoderParameters encodeurs = new EncoderParameters(2);
                // parametre qualite
                EncoderParameter qualite = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,quality);
                // Parametre compression 
                EncoderParameter compression = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, compress);
                // remplir tableau parametre
                encodeurs.Param[0] = qualite;
                encodeurs.Param[1] = compression;

                using (MemoryStream stm = new MemoryStream())
                {
                    img.Save(stm, codec[1], encodeurs);
                    if (Cnx.sendArray(stm.ToArray(), "04")) { Console.WriteLine("success ");  }
                    
                }

                Thread.Sleep(sleeptime);
            } while (keepGoing);

        }
        Bitmap SaveInMemory(Stream stream, long quality, Bitmap myBitmap)
        {
            ImageCodecInfo myImageCodecInfo;
            Encoder myEncoder;
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;

            // Get an ImageCodecInfo object that represents the JPEG codec.
            myImageCodecInfo = GetEncoderInfo("image/jpeg");

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

            // EncoderParameter object in the array.
            using (myEncoderParameters = new EncoderParameters(1))
            {
                // Save the bitmap as a JPEG file with quality level.            
                myEncoderParameter = new EncoderParameter(myEncoder, quality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                myBitmap.Save(stream, myImageCodecInfo, myEncoderParameters);
            }

            return myBitmap;
        }
Ejemplo n.º 10
0
 public bool SaveImageForSpecifiedQuality(System.Drawing.Image sourceImage, string savePath, int imageQualityValue)
 {
     //以下代码为保存图片时,设置压缩质量
     EncoderParameters encoderParameters = new EncoderParameters();
     EncoderParameter encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, imageQualityValue);
     encoderParameters.Param[0] = encoderParameter;
     try
     {
         ImageCodecInfo[] ImageCodecInfoArray = ImageCodecInfo.GetImageEncoders();
         ImageCodecInfo jpegImageCodecInfo = null;
         for (int i = 0; i < ImageCodecInfoArray.Length; i++)
         {
             if (ImageCodecInfoArray[i].FormatDescription.Equals("JPEG"))
             {
                 jpegImageCodecInfo = ImageCodecInfoArray[i];
                 break;
             }
         }
         sourceImage.Save(savePath, jpegImageCodecInfo, encoderParameters);
         return true;
     }
     catch
     {
         return false;
     }
 }
Ejemplo n.º 11
0
        public static byte[] CreateThumbnail(byte[] PassedImage, int newWidth, int newHeight)
        {
            byte[] ReturnedThumbnail;

            using (MemoryStream StartMemoryStream = new MemoryStream(), NewMemoryStream = new MemoryStream()) {
                // write the string to the stream
                StartMemoryStream.Write(PassedImage, 0, PassedImage.Length);

                // create the start Bitmap from the MemoryStream that contains the image
                Bitmap startBitmap = new Bitmap(StartMemoryStream);

                // create a new Bitmap with dimensions for the thumbnail.
                Bitmap newBitmap = new Bitmap(newWidth, newHeight);

                // Copy the image from the START Bitmap into the NEW Bitmap.
                // This will create a thumnail size of the same image.
                newBitmap = ResizeImage(startBitmap, newWidth, newHeight);

                // Save this image to the specified stream in the specified format.
                System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);
                myEncoderParameters.Param[0] = myEncoderParameter;
                ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);

                newBitmap.Save(NewMemoryStream, jpgEncoder, myEncoderParameters);

                // Fill the byte[] for the thumbnail from the new MemoryStream.
                ReturnedThumbnail = NewMemoryStream.ToArray();
            }

            // return the resized image as a string of bytes.
            return ReturnedThumbnail;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets the bytes.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="imageFormat">The image format.</param>
        /// <param name="qualityLevel">The quality level.
        /// <remarks>
        /// A quality level of 0 corresponds to the greatest compression, and a quality level of 100 corresponds to the least compression.
        /// https://msdn.microsoft.com/library/bb882583(v=vs.110).aspx
        /// </remarks></param>
        /// <returns>System.Byte[].</returns>
        /// <exception cref="OperationFailureException">GetBytes</exception>
        public static byte[] GetBytes(this Bitmap image, ImageFormat imageFormat = null, long qualityLevel = 100)
        {
            try
            {
                image.CheckNullObject("image");

                if (imageFormat == null)
                {
                    imageFormat = ImageFormat.Jpeg;
                }

                if (qualityLevel > 100 || qualityLevel < 1)
                {
                    qualityLevel = 100;
                }

                using (var memoryStream = new MemoryStream())
                {
                    var jpegEncoder = GetImageEncoder(imageFormat);
                    var encoder = Encoder.Quality;
                    var encoderParameters = new EncoderParameters(1);

                    var myEncoderParameter = new EncoderParameter(encoder, qualityLevel);
                    encoderParameters.Param[0] = myEncoderParameter;
                    image.Save(memoryStream, jpegEncoder, encoderParameters);

                    return memoryStream.ToBytes();
                }
            }
            catch (Exception ex)
            {
                throw ex.Handle();
            }
        }
Ejemplo n.º 13
0
        public static void BmpSave(Bitmap newBmp, string outFile)
        {
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

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

            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];//设置JPEG编码
                    break;
                }
            }

            if (jpegICI != null)
            {
                newBmp.Save(outFile, jpegICI, encoderParams);
            }
            else
            {
                newBmp.Save(outFile, ImageFormat.Jpeg);
            }
            newBmp.Dispose();
        }
Ejemplo n.º 14
0
 public ActionResult Thumbnail(string path)
 {
     var myCallback =
         new Image.GetThumbnailImageAbort(ThumbnailCallback);
     var paths = new List<string>(2);
     BuildPath(path, out folderPath, out resourcePath);
     var folder = session.OpenFolder(folderPath + "/");
     var resource = folder.GetResource(resourcePath + "/");
     var sourceStream = resource.GetReadStream();
     Bitmap bitmap = null;
     try
     {
         bitmap = new Bitmap(sourceStream);
     }
     catch (Exception)
     {
         var fs = new FileStream(Server.MapPath("~/Content/kendo/2014.2.716/Bootstrap/imagebrowser.png"), FileMode.Open);
         var tempBs = new byte[fs.Length];
         fs.Read(tempBs, 0, tempBs.Length);
         return new FileContentResult(tempBs, "image/jpeg");
     }
     var myThumbnail = bitmap.GetThumbnailImage(84, 70, myCallback, IntPtr.Zero);
     var ms = new MemoryStream();
     var myEncoderParameters = new EncoderParameters(1);
     var myEncoderParameter = new EncoderParameter(Encoder.Quality, 25L);
     myEncoderParameters.Param[0] = myEncoderParameter;
     myThumbnail.Save(ms, GetEncoderInfo("image/jpeg"), myEncoderParameters);
     ms.Position = 0;
     var bytes = ms.ToArray();
     return new FileContentResult(bytes, "image/jpeg");
 }
Ejemplo n.º 15
0
        private void convertToPng(string sourcedir, string sourceFile, string sourceDirandFile)
        {
            try
            {
                // Load the image.
                System.Drawing.Image image1 = System.Drawing.Image.FromFile(sourceDirandFile);
                if (filetype == "jpg")
                {
                    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, 100L);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    image1.Save(sourcedir + "\\" + sourceFile + ".jpg", jgpEncoder, myEncoderParameters);

                }
                else if (filetype == "png")
                {
                    // Save the image in PNG format.
                    image1.Save(sourcedir + "\\" + sourceFile + ".png", System.Drawing.Imaging.ImageFormat.Png);
                }
                progressBar1.Increment(1);
            }
            catch
            {
                Console.WriteLine("Crap");
            }
        }
Ejemplo n.º 16
0
 public static void Save(Image image, int maxWidth, int maxHeight, int quality, string filePath)
 {
     if (image != null || !image.Equals(0))
     {
         int originalWidth = image.Width;
         int originalHeight = image.Height;
         float ratioX = maxWidth / (float)originalWidth;
         float ratioY = maxHeight / (float)originalHeight;
         float ratio = Math.Min(ratioX, ratioY);
         int newWidth = (int)(originalWidth * ratio);
         int newHeight = (int)(originalHeight * ratio);
         newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
         using (Graphics graphics = Graphics.FromImage(newImage))
         {
             graphics.CompositingQuality = CompositingQuality.HighQuality;
             graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
             graphics.SmoothingMode = SmoothingMode.HighQuality;
             graphics.DrawImage(image, 0, 0, newWidth, newHeight);
         }
         ImageCodecInfo imageCodecInfo = GetEncoderInfo(ImageFormat.Jpeg);
         System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
         encoderParameters = new EncoderParameters(1);
         EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
         encoderParameters.Param[0] = encoderParameter;
         newImage.Save(filePath, imageCodecInfo, encoderParameters);
     }
 }
        /// <summary>
        /// 調整圖片壓縮解析度
        /// </summary>
        public static string ToBase64String_x1(Bitmap newBmp, ImageFormat iFormat)
        {
            MemoryStream ms = new MemoryStream();

            //save
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 30L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            newBmp.Save(ms, jgpEncoder, myEncoderParameters);

            //Bitmap new2Bmp = new Bitmap(ms);
            //new2Bmp.Save(@"c:\test002.jpg", iFormat);

            //newBmp.Save(ms, iFormat);
            ms.Seek(0, SeekOrigin.Begin);

            //建立一個byte
            //並且定義長度為MemoryStream的長度
            byte[] bytes = new byte[ms.Length];
            //MemoryStream讀取資料
            ms.Read(bytes, 0, (int)ms.Length);
            ms.Close();

            return Convert.ToBase64String(bytes);
        }
Ejemplo n.º 18
0
        public static void StoreIcon(string extension, string path, string mimeType)
        {
            if (!File.Exists(path))
            {
                try
                {
                    if (!Directory.Exists(Path.GetDirectoryName(path)))
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                    Bitmap image = IconHandler.IconFromExtension(extension, IconSize.Small);

                    System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
                    long quality = 100;
                    EncoderParameter ratio = new EncoderParameter(qualityEncoder, quality);
                    EncoderParameters codecParams = new EncoderParameters(1);
                    codecParams.Param[0] = ratio;
                    ImageCodecInfo mimeCodecInfo = null;
                    foreach (ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders())
                    {
                        if (codecInfo.MimeType == mimeType)
                        {
                            mimeCodecInfo = codecInfo;
                            break;
                        }
                    }
                    if (mimeCodecInfo != null)
                        image.Save(path, mimeCodecInfo, codecParams); // Save to JPG
                }
                catch (Exception ex)
                {
                    logger.LogException(LogLevel.Error, "Failed to create icon", ex);
                }
            }
        }
Ejemplo n.º 19
0
 public static EncoderParameters getParameters(int jpegQuality, ScreenshotFormat format)
 {
     EncoderParameters result;
     switch(format)
     {
         case ScreenshotFormat.BMP:
             result = new EncoderParameters(1);
             result.Param[0] = new EncoderParameter(Encoder.ColorDepth, 24);
             break;
         case ScreenshotFormat.JPEG:
             result = new EncoderParameters(1);
             result.Param[0] = new EncoderParameter(Encoder.Quality, jpegQuality);
             break;
         case ScreenshotFormat.TIFF:
             result = new EncoderParameters(2);
             EncoderParameter parameter = 
                 new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW);
             result.Param[0] = parameter;
             parameter = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.LastFrame);
             result.Param[1] = parameter;
             break;
         default:
             result = new EncoderParameters(2);
             result.Param[0] = new EncoderParameter(Encoder.Compression,(long)EncoderValue.CompressionCCITT4);
             result.Param[1] = new EncoderParameter(Encoder.ColorDepth, (long)24);
             break;
     }
     return result;
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Takes a screen-size + internal bezel width sized bitmap and crops it to remove the area taken up by the bezels. Making the image appear as if it was seen through a window.
        /// </summary>
        /// <param name="filePaths">The file paths.</param>
        /// <remarks>
        /// Writes a file of the same name with -wallpapered appended to the end in JPEG format to the same location as the source.
        /// </remarks>
        public static void Main(String[] filePaths)
        {
            if(filePaths.Length < 1)
            {
                DisplayInstructions();
                return;
            }

            foreach(var filePath in filePaths)
            {
                String fileName = Path.GetFileNameWithoutExtension(filePath);
                String fileDirectory = Path.GetDirectoryName(filePath);
                String jpgFilePath = String.Format("{0}{1}{2}-wallpapered.jpg", fileDirectory, Path.DirectorySeparatorChar, fileName);

                using(Bitmap sourceBitmap = new Bitmap(filePath))
                {
                    //Check size
                    if(sourceBitmap.Width != TotalMonitorWidth || sourceBitmap.Height != MaximumMonitorHeight)
                    {
                        DisplayInstructions();
                        continue;
                    }

                    Bitmap wallpaper = CreateWallpaper(sourceBitmap);

                    //Save as JPEG
                    var jpegImageCodecInfo = GetEncoderInfo("image/jpeg");
                    var qualityEncoder = Encoder.Quality;
                    var encoderParameters = new EncoderParameters(1);
                    var encoderParameter = new EncoderParameter(qualityEncoder, (Int64)JPEGQuality);
                    encoderParameters.Param[0] = encoderParameter;
                    wallpaper.Save(jpgFilePath, jpegImageCodecInfo, encoderParameters);
                }
            }
        }
Ejemplo n.º 21
0
        public byte[] Capture()
        {
            if (_camDriver.IsVideoStarted() == false)
            {
                _camDriver.StartVideo();
            }
            // wait for the camera to capture something
            //if (_camDriver.Capture())
            //{
            _camEvent.WaitOne();

            if (_captureStream == null)
            {
                _captureStream = new MemoryStream();
            }

            ImageCodecInfo jpgEncoder = ImageCodecInfo.GetImageEncoders().Single(x => x.FormatDescription == "JPEG");
            System.Drawing.Imaging.Encoder encoder2 = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1);
            EncoderParameter parameter = new EncoderParameter(encoder2, 50L);
            parameters.Param[0] = parameter;

            _captureStream.Seek(0, SeekOrigin.Begin);
            _camImage.Save(_captureStream, jpgEncoder, parameters);
            //_camImage.Save(_captureStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] buffer = new byte[_captureStream.Length];
            Console.WriteLine("Sending image with size " + buffer.Length);
            //_captureStream.Read(buffer,0,(int)_captureStream.Length);
            buffer = _captureStream.ToArray();

            return buffer;

            //return b;
        }
Ejemplo n.º 22
0
    /// <summary>
    /// 指定されたファイルを品質を指定してJPEGで保存する
    /// </summary>
    /// <param name="fileName">画像ファイル名</param>
    /// <param name="quality">品質</param>
    public static void SaveImage(this Image img, string fileName, int quality)
    {
        //画像ファイルを読み込む
        Bitmap bmp = img as Bitmap;

        //EncoderParameterオブジェクトを1つ格納できる
        //EncoderParametersクラスの新しいインスタンスを初期化
        //ここでは品質のみ指定するため1つだけ用意する
        var eps = new EncoderParameters(1);

        //品質を指定
        System.Drawing.Imaging.EncoderParameter ep =
            new System.Drawing.Imaging.EncoderParameter(
                System.Drawing.Imaging.Encoder.Quality, quality);
        //EncoderParametersにセットする
        eps.Param[0] = ep;

        //イメージエンコーダに関する情報を取得する
        var ici = GetEncoderInfo("image/jpeg");

        //新しいファイルの拡張子を取得する
        string ext = ici.FilenameExtension.Split(';')[0];

        ext = Path.GetExtension(ext).ToLower();

        //保存するファイル名を決定(拡張子を変える)
        string saveName = Path.ChangeExtension(fileName, ext);

        //保存する
        bmp.Save(saveName, ici, eps);
        fileName = saveName;
    }
        public static bool TakeScreenshot(int quality_quotient)
        {
            Bitmap resultant = null;
            Graphics gfxScreenshot = null;
            latestScreenshot = new MemoryStream();

            try
            {
                resultant = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
                gfxScreenshot = Graphics.FromImage(resultant);
                gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
            }
            catch
            {
                return false;
            }

            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);

            // Setting the picture quality
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, (long)quality_quotient);
            myEncoderParameters.Param[0] = myEncoderParameter;

            resultant.Save(latestScreenshot, jgpEncoder, myEncoderParameters);

            return true;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Saves the Bitmap to the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        public void Save(HttpResponse response, string filename)
        {
            if (_thumb != null) {
                var ext = Services.Paths.Extension(filename).ToLower();
                if (ext == "jpg" || ext == "jpeg" || ext == "jpe") {
                    // JPEG Optimizing
                    EncoderParameters encoderParams = new EncoderParameters();
                    long[] quality = new long[1];
                    quality[0] = 75;
                    EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, quality);
                    encoderParams.Param[0] = encoderParam;

                    ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo codec = encoders.Where(
                         p => p.FormatDescription.Equals("JPEG")).SingleOrDefault();
                    // Save to Specified Stream
                    response.ContentType = "image/jpeg";
                    using (var m = new MemoryStream()) {
                        _thumb.Save(m, codec, encoderParams);
                        m.Seek(0, SeekOrigin.Begin);
                        m.CopyTo(response.OutputStream);
                        Services.Files.Save(m, filename); // cache result
                    }
                } else {
                    response.ContentType  = "image/png";
                    using (var m = new MemoryStream()) {
                        _thumb.Save(m, ImageFormat.Png);
                        m.Seek(0, SeekOrigin.Begin);
                        m.CopyTo(response.OutputStream);
                        Services.Files.Save(m, filename); // cache result
                    }
                }
            }
        }
Ejemplo n.º 25
0
        private void sendscreen(string res, int v)
        {
            try
            {
                int width  = Convert.ToInt32(res.Split('x')[0]);
                int height = Convert.ToInt32(res.Split('x')[1]);

                using (Bitmap b = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height))
                {
                    using (Graphics g = Graphics.FromImage(b))
                    {
                        g.CopyFromScreen(0, 0, 0, 0, b.Size);
                        using (Image tmp = b.GetThumbnailImage(width, height, null, System.IntPtr.Zero))
                        {
                            using (Bitmap thumBitmap = new Bitmap(tmp))
                            {
                                ImageCodecInfo    jgpEncoder          = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
                                EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
                                EncoderParameter  myEncoderParameter  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, v);
                                myEncoderParameters.Param[0] = myEncoderParameter;

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    thumBitmap.Save(ms, jgpEncoder, myEncoderParameters);
                                    Send("RemoteDesktop" + Convert.ToBase64String(ms.ToArray()));
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 26
0
        /// <summary>  
        /// Saves an image as a jpeg image, with the given quality  
        /// </summary>  
        /// <param name="path">Path to which the image would be saved.</param>  
        /// <param name="quality">An integer from 0 to 100, with 100 being the  
        /// highest quality</param>  
        /// <exception cref="ArgumentOutOfRangeException"> 
        /// An invalid value was entered for image quality. 
        /// </exception> 
        public void SavePNG(Image[] images, int quality, string workspace)
        {
            //ensure the quality is within the correct range
            if ((quality < 0) || (quality > 100))
            {
                //create the error message
                string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality.  A value of {0} was specified.", quality);
                //throw a helpful exception
                throw new ArgumentOutOfRangeException(error);
            }

            //create an encoder parameter for the image quality
            var qualityParam = new EncoderParameter(Encoder.Quality, quality);

            //get the jpeg codec
            ImageCodecInfo jpegCodec = converter.GetEncoderInfo("image/png");

            //create a collection of all parameters that we will pass to the encoder
            var encoderParams = new EncoderParameters(1);
            //set the quality parameter for the codec
            encoderParams.Param[0] = qualityParam;
            //save the images using the codec and the parameters
            //each image will be saved into it's folder
            for (int i = 0; i < images.Length; i++)
            {
                for (int j = 0; j < dirs.Length; j++)
                {
                    string desination = (path + splitter + workspace + dirs[i]);
                    Check(desination);
                    images[i].Save(desination, jpegCodec, encoderParams);
                }

            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Method to resize, convert and save the image.
        /// </summary>
        /// <param name="image">Bitmap image.</param>
        /// <param name="maxWidth">resize width.</param>
        /// <param name="maxHeight">resize height.</param>
        /// <param name="quality">quality setting value.</param>
        /// <param name="filePathDest">file path.</param>      
        public static bool Resize(string filePathSource, int maxWidth, int maxHeight, int quality, string filePathDest)
        {
            bool bOk = true;
            try
            {
                Bitmap image = new Bitmap(filePathSource);

                // Get the image's original width and height
                int originalWidth = image.Width;
                int originalHeight = image.Height;

                //Check size
                if (originalWidth <= maxWidth && originalHeight <= maxHeight)
                {
                    return false; //No need to resize
                }

                // To preserve the aspect ratio
                float ratioX = (float)maxWidth / (float)originalWidth;
                float ratioY = (float)maxHeight / (float)originalHeight;
                float ratio = Math.Min(ratioX, ratioY);

                // New width and height based on aspect ratio
                int newWidth = (int)(originalWidth * ratio);
                int newHeight = (int)(originalHeight * ratio);

                // Convert other formats (including CMYK) to RGB.
                Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);

                // Draws the image in the specified size with quality mode set to HighQuality
                using (Graphics graphics = Graphics.FromImage(newImage))
                {
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    graphics.DrawImage(image, 0, 0, newWidth, newHeight);
                }

                // Get an ImageCodecInfo object that represents the JPEG codec.
                ImageCodecInfo imageCodecInfo = GetEncoderInfo(ImageFormat.Jpeg);

                // Create an Encoder object for the Quality parameter.
                Encoder encoder = Encoder.Quality;

                // Create an EncoderParameters object. 
                EncoderParameters encoderParameters = new EncoderParameters(1);

                // Save the image as a JPEG file with quality level.
                EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
                encoderParameters.Param[0] = encoderParameter;
                newImage.Save(filePathDest, imageCodecInfo, encoderParameters);
            }
            catch
            {
                bOk = false;
            }

            return bOk;
        }
 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.º 29
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.º 30
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.º 31
0
        /// <summary>
        /// 保存扫描的申请单
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        private bool SaveScanImg(Bitmap bmp)
        {
            //创建一个扫描图像类
            ScanData oneScan = new ScanData();

            oneScan.申请ID      = _str申请ID;
            oneScan.扫描ID      = SqlHelper.GetNumGuid().ToString();
            oneScan.扫描信息.存储ID = 存储ID;
            oneScan.扫描信息.扫描人  = 扫描人;
            oneScan.扫描信息.扫描时间 = _scanModel.GetServerDate();
            oneScan.扫描信息.文件名  = Guid.NewGuid().ToString("N");
            oneScan.扫描信息.申请日期 = 申请日期;
            oneScan.扫描信息.CopyBasePro(oneScan);

            try
            {
                //保存临时文件
                var eps = new System.Drawing.Imaging.EncoderParameters(1);
                var ep  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
                eps.Param[0] = ep;
                var jpsEncoder = GetEncoder(ImageFormat.Jpeg);

                FTPFileHelp ftpHelper = new FTPFileHelp();
                initFTP(_dbQuery, 存储ID, out ftpHelper);

                string vPath   = ftpHelper.VPath + "//" + oneScan.扫描信息.申请日期.ToString("yyyyMMdd") + "//" + oneScan.申请ID + "//apply//";
                string tmpFile = System.Windows.Forms.Application.StartupPath + @"\Temp" + vPath.Replace("//", "\\");
                if (Directory.Exists(tmpFile) == false)
                {
                    Directory.CreateDirectory(tmpFile);
                }

                tmpFile = tmpFile + oneScan.扫描信息.文件名 + ".jpg";
                bmp.Save(tmpFile, jpsEncoder, eps);
                //释放资源
                ep.Dispose();
                eps.Dispose();

                //上传FTP
                FileInfo fi = new FileInfo(tmpFile);
                ftpHelper.MakeDirectory(vPath);
                if (ftpHelper.FileUpLoad(vPath + oneScan.扫描信息.文件名 + ".jpg", fi) == true)
                {
                    //存入数据库
                    _scanModel.SaveScanImage(oneScan);
                }
                else
                {
                    return(false);
                }
                //ftpHelper.disConnect(); 没有关闭连接的方法吗?
            }
            catch (Exception ex)
            {
                MsgBox.ShowException(ex, this);
            }
            return(true);
        }
Ejemplo n.º 32
0
        public static void ResizeImg(int destWidth, int destHeight, string filePath, string saveFilePath)
        { //重新設定大小
            System.Drawing.Image sourImage;
            WebClient            webC = new WebClient();

            sourImage = System.Drawing.Image.FromStream(webC.OpenRead(filePath));
            sourImage = RotateImage(sourImage);
            webC.Dispose();
            webC = null;

            int width = 0, height = 0;
            //按比例縮放
            int sourWidth  = sourImage.Width;
            int sourHeight = sourImage.Height;

            if (sourHeight > destHeight || sourWidth > destWidth)
            {
                if ((sourWidth * destHeight) > (sourHeight * destWidth))
                {
                    width  = destWidth;
                    height = (destWidth * sourHeight) / sourWidth;
                }
                else
                {
                    height = destHeight;
                    width  = (sourWidth * destHeight) / sourHeight;
                }
            }
            else
            {
                width  = sourWidth;
                height = sourHeight;
            }

            Bitmap   destBitmap = new Bitmap(width, height);
            Graphics g          = Graphics.FromImage(destBitmap);

            g.Clear(Color.Transparent);
            //設置畫布的描繪品質
            // g.Clear(Color.Transparent);
            g.Clear(Color.Black);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(sourImage, new Rectangle(0, 0, width, height), new Rectangle(0, 0, sourWidth, sourHeight), GraphicsUnit.Pixel);
            g.Dispose();
            //設置壓縮品質
            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;
            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            sourImage.Dispose();
            sourImage = null;
            destBitmap.Save(saveFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            destBitmap.Dispose();
            destBitmap = null;
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Handles cropping of images, scales the cropped images to standard dimensions
 /// configured in the AppSettings file
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="sourcefolder"></param>
 /// <param name="targetfolder"></param>
 /// <param name="imgfolder"></param>
 /// <param name="X"></param>
 /// <param name="Y"></param>
 /// <param name="W"></param>
 /// <param name="H"></param>
 /// <returns></returns>
 public String CropImage(String filename, String sourcefolder, String targetfolder, String imgfolder, int X, int Y, int W, int H)
 {
     String result = "";
     // enforce final cropped images to have fixed dimensions
     int croppedfinalw, croppedfinalh;
     croppedfinalh = Convert.ToInt32(Settings.AppSettings.passheight);
     croppedfinalw = Convert.ToInt32(Settings.AppSettings.passwidth);
     try
     {
         if (!imgfolder.EndsWith("\\"))
         {
             imgfolder += "\\";
         }
         String sourcepath = imgfolder + sourcefolder + "\\";
         Bitmap image1 = (Bitmap)Image.FromFile(sourcepath + filename, true);
         Rectangle rect = new Rectangle(X, Y, W, H);
         Bitmap cropped = image1.Clone(rect, image1.PixelFormat);
         // dispose original image in case we need to overwrite it below
         if (image1 != null)
         {
             image1.Dispose();
         }
         Bitmap finalcropped= new Bitmap(croppedfinalw, croppedfinalh);
         Graphics gr_finalcropped  = Graphics.FromImage(finalcropped);
         SolidBrush sb = new SolidBrush(System.Drawing.Color.White);
         gr_finalcropped.FillRectangle(sb, 0, 0, finalcropped.Width, finalcropped.Height);
         gr_finalcropped.DrawImage(cropped, 0, 0, finalcropped.Width, finalcropped.Height);
         try
         {
             ImageCodecInfo codecencoder  = GetEncoder("image/jpeg");
             int quality = 92;
             EncoderParameters encodeparams  = new EncoderParameters(1);
             EncoderParameter qualityparam = new EncoderParameter(Encoder.Quality, quality);
             encodeparams.Param[0] = qualityparam;
             finalcropped.SetResolution(240, 240);
             sourcepath = sourcepath.Replace(sourcefolder, targetfolder);
             finalcropped.Save(sourcepath + filename, codecencoder, encodeparams);
             result = "OK - File cropped";
         }
         catch(Exception ex)
         {
             result = "ERROR: there was a problem saving the image. " + ex.Message;
         }
         if (cropped != null)
         {
             cropped.Dispose();
         }
         if (finalcropped != null)
         {
             finalcropped.Dispose();
         }
     }
     catch(Exception ex)
     {
         result = "ERROR: that was not an image we could process. " + ex.Message;
     }
     return result;
 }
Ejemplo n.º 34
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.º 35
0
        public static void Save(ImageFormat format, ImageData data) {
            ImageCodecInfo codec = GetEncoder(ImageFormat.Jpeg);
            Encoder quality = Encoder.Quality;
            EncoderParameters encoderArray = new EncoderParameters(1);
            EncoderParameter encoder = new EncoderParameter(quality, 85L);
            encoderArray.Param[0] = encoder;

            data.M_bitmap.Save(data.M_outputFilename, codec, encoderArray);
        }
Ejemplo n.º 36
0
 public static System.Drawing.Image ZoomImage(System.Drawing.Image bitmap, int destWidth, int destHeight)
 { //等比縮放
     try
     {
         System.Drawing.Image sourImage = bitmap;
         bitmap = RotateImage(bitmap);
         int width = 0, height = 0;
         //按比例縮放
         int sourWidth  = sourImage.Width;
         int sourHeight = sourImage.Height;
         if (sourHeight > destHeight || sourWidth > destWidth)
         {
             if ((sourWidth * destHeight) > (sourHeight * destWidth))
             {
                 width  = destWidth;
                 height = (destWidth * sourHeight) / sourWidth;
             }
             else
             {
                 height = destHeight;
                 width  = (sourWidth * destHeight) / sourHeight;
             }
         }
         else
         {
             width  = sourWidth;
             height = sourHeight;
         }
         Bitmap   destBitmap = new Bitmap(destWidth, destHeight);
         Graphics g          = Graphics.FromImage(destBitmap);
         g.Clear(Color.Transparent);
         //設置畫布的描繪品質
         // webpic = Image_ChangeOpacity(webpic, 0f);
         g.Clear(Color.Transparent);
         // g.Clear(Color.Black);
         g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
         g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
         g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
         g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
         //高度置中
         //g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height), width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
         //齊底
         g.Dispose();
         //設置壓縮品質
         System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
         long[] quality = new long[1];
         quality[0] = 100;
         System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
         encoderParams.Param[0] = encoderParam;
         sourImage.Dispose();
         return(destBitmap);
     }
     catch
     {
         return(bitmap);
     }
 }
Ejemplo n.º 37
0
 public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
 {
     ImageCodecInfo encoderInfo = ImageThumbnail.GetEncoderInfo("image/jpeg");
     Encoder quality = Encoder.Quality;
     EncoderParameters encoderParameters = new EncoderParameters(1);
     EncoderParameter encoderParameter = new EncoderParameter(quality, level);
     encoderParameters.Param[0] = encoderParameter;
     srcBitmap.Save(destStream, encoderInfo, encoderParameters);
 }
Ejemplo n.º 38
0
        private void KucultveKaydet()
        {
            foreach (Control Ctrl in this.Controls)
            {
                ((Control)Ctrl).Enabled = false;
            }
            progressBar1.Maximum = listBox1.Items.Count;
            progressBar1.Value   = 0;
            label5.Enabled       = true;
            label5.Visible       = true;

            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                string resimAdi = listBox1.GetItemText(listBox1.Items[i]);
                using (Bitmap img = new Bitmap(resimAdi))
                {
                    double aspectRatio = Convert.ToDouble(img.Height) / img.Width;
                    int    en = 0, boy = 0;
                    if (img.Width > img.Height)
                    {
                        en  = Convert.ToInt32(textBox1.Text);
                        boy = Convert.ToInt32(aspectRatio * en);
                    }
                    else
                    {
                        boy = Convert.ToInt32(textBox1.Text);
                        en  = Convert.ToInt32(boy / aspectRatio);
                    }
                    if (!checkBox2.Checked)
                    {
                        boy = Convert.ToInt32(textBox2.Text);
                    }
                    Size   newsize  = new Size(en, boy);
                    Bitmap thumbimg = new Bitmap(img, newsize);
                    string newname  = resimAdi + "_k";

                    ImageCodecInfo    ici   = GetEncoderInfo(img.RawFormat);
                    EncoderParameter  encp  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Convert.ToInt64(textBox3.Text.Trim()));
                    EncoderParameter  encp1 = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, Convert.ToInt64(comboBox1.SelectedItem.ToString()));
                    EncoderParameters encps = new EncoderParameters(2);
                    encps.Param[0] = encp;
                    encps.Param[1] = encp1;

                    thumbimg.Save(resimAdi.Substring(0, resimAdi.LastIndexOf(".")) + "_k" + resimAdi.Substring(resimAdi.LastIndexOf(".")), ici, encps);
                    progressBar1.Value = i;
                }
            }

            listBox1.Items.Clear();
            label5.Visible     = false;
            progressBar1.Value = 0;
            foreach (Control Ctrl in this.Controls)
            {
                ((Control)Ctrl).Enabled = true;
            }
        }
Ejemplo n.º 39
0
        private void SaveSinglePage(Bitmap bitMap)
        {
            ImageCodecInfo codecInfo = getCodecForstring("TIFF");

            System.Drawing.Imaging.EncoderParameters iparams    = new System.Drawing.Imaging.EncoderParameters(1);
            System.Drawing.Imaging.Encoder           iparam     = System.Drawing.Imaging.Encoder.Compression;
            System.Drawing.Imaging.EncoderParameter  iparamPara = new System.Drawing.Imaging.EncoderParameter(iparam, (long)(System.Drawing.Imaging.EncoderValue.CompressionCCITT4));
            iparams.Param[0] = iparamPara;
            bitMap.Save(this.m_FileName, codecInfo, iparams);
        }
Ejemplo n.º 40
0
 public static void SaveJpeg(string path, Image image, long quality)
 {
     using (var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1))
         using (var encoderParameter = new System.Drawing.Imaging.EncoderParameter(Encoder.Quality, quality))
         {
             ImageCodecInfo codecInfo = ImageCodecInfo.GetImageDecoders().First(codec => codec.FormatID == ImageFormat.Jpeg.Guid);
             encoderParameters.Param[0] = encoderParameter;
             image.Save(path, codecInfo, encoderParameters);
         }
 }
Ejemplo n.º 41
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.º 42
0
        private Bitmap ZoomImage(Bitmap bitmap, int destHeight, int destWidth)
        {
            try
            {
                System.Drawing.Image sourImage = bitmap;
                int width = 0, height = 0;
                //按比例缩放
                int sourWidth  = sourImage.Width;
                int sourHeight = sourImage.Height;
                if (sourHeight > destHeight || sourWidth > destWidth)
                {
                    if ((sourWidth * destHeight) > (sourHeight * destWidth))
                    {
                        width  = destWidth;
                        height = (destWidth * sourHeight) / sourWidth;
                    }
                    else
                    {
                        height = destHeight;
                        width  = (sourWidth * destHeight) / sourHeight;
                    }
                }
                else
                {
                    width  = sourWidth;
                    height = sourHeight;
                }
                Bitmap   destBitmap = new Bitmap(destWidth, destHeight);
                Graphics g     = Graphics.FromImage(destBitmap);
                g.Clear(Color.Transparent);
                //设置画布的描绘质量
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
                g.Dispose();
                //设置压缩质量
                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                long[] quality = new long[1];
                quality[0] = 100;
                System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                sourImage.Dispose();
                bitmap.Dispose();
                sourImage.Dispose();
                return(destBitmap);
            }
            catch
            {
                return(bitmap);
            }
        }
Ejemplo n.º 43
0
        public static void Resize_Picture(ref Bitmap bmp, string Des, int FinalWidth, int FinalHeight, int ImageQuality)
        {
            System.Drawing.Bitmap   NewBMP;
            System.Drawing.Graphics graphicTemp;

            int iWidth;
            int iHeight;

            if ((FinalHeight == 0) && (FinalWidth != 0))
            {
                iWidth  = FinalWidth;
                iHeight = (bmp.Size.Height * iWidth / bmp.Size.Width);
            }
            else if ((FinalHeight != 0) && (FinalWidth == 0))
            {
                iHeight = FinalHeight;
                iWidth  = (bmp.Size.Width * iHeight / bmp.Size.Height);
            }
            else
            {
                iWidth  = FinalWidth;
                iHeight = FinalHeight;
            }

            NewBMP      = new System.Drawing.Bitmap(iWidth, iHeight);
            graphicTemp = System.Drawing.Graphics.FromImage(NewBMP);
            graphicTemp.CompositingMode    = System.Drawing.Drawing2D.CompositingMode.SourceOver;
            graphicTemp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphicTemp.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphicTemp.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphicTemp.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            graphicTemp.DrawImage(bmp, 0, 0, iWidth, iHeight);
            graphicTemp.Dispose();
            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            System.Drawing.Imaging.EncoderParameter  encoderParam  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQuality);
            encoderParams.Param[0] = encoderParam;
            System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();

            //for (int fwd = 0; fwd <= arrayICI.Length - 1; fwd++)
            //{
            //    if (arrayICI[fwd].FormatDescription.Equals("JPEG"))
            //    {
            //        NewBMP.Save(, arrayICI[fwd], encoderParams);
            //    }
            //}

            bmp = NewBMP;

            //NewBMP.Dispose();
            //bmp.Dispose();
        }
Ejemplo n.º 44
0
        public static void SaveJpeg(string path, Image img, int quality)
        {
            if (quality < 0 || quality > 100)
            {
                throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
            }

            // Encoder parameter for image quality
            EncoderParameter qualityParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            // JPEG image codec
            ImageCodecInfo    jpegCodec     = GetEncoderInfo("image/jpeg");
            EncoderParameters encoderParams = new EncoderParameters(1);

            encoderParams.Param[0] = qualityParam;
            img.Save(path, jpegCodec, encoderParams);
        }
Ejemplo n.º 45
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();
     }
 }
Ejemplo n.º 46
0
        public static System.Drawing.Bitmap GetThumbnail(System.Drawing.Bitmap b, int destHeight, int destWidth)
        {
            System.Drawing.Imaging.ImageFormat rawFormat = b.RawFormat;
            int width  = b.Width;
            int height = b.Height;
            int num;
            int num2;

            if (height > destHeight || width > destWidth)
            {
                if (width * destHeight < height * destWidth)
                {
                    num  = destWidth;
                    num2 = destWidth * height / width;
                }
                else
                {
                    num2 = destHeight;
                    num  = width * destHeight / height;
                }
            }
            else
            {
                num  = destWidth;
                num2 = destHeight;
            }
            System.Drawing.Bitmap   bitmap   = new System.Drawing.Bitmap(destWidth, destHeight);
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
            graphics.Clear(System.Drawing.Color.Transparent);
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphics.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(b, new System.Drawing.Rectangle((destWidth - num) / 2, (destHeight - num2) / 2, num, num2), 0, 0, b.Width, b.Height, System.Drawing.GraphicsUnit.Pixel);
            graphics.Dispose();
            System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters();
            long[] value = new long[]
            {
                100L
            };
            System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, value);
            encoderParameters.Param[0] = encoderParameter;
            b.Dispose();
            return(bitmap);
        }
Ejemplo n.º 47
0
        private void SaveMultiPage(List <Bitmap> bitMaps)
        {
            ImageCodecInfo codecInfo = getCodecForstring("TIFF");

            this.ConvertToBitonal(bitMaps);

            System.Drawing.Imaging.Encoder           saveEncoder;
            System.Drawing.Imaging.Encoder           compressionEncoder;
            System.Drawing.Imaging.EncoderParameter  SaveEncodeParam;
            System.Drawing.Imaging.EncoderParameter  CompressionEncodeParam;
            System.Drawing.Imaging.EncoderParameters EncoderParams = new System.Drawing.Imaging.EncoderParameters(2);

            saveEncoder        = System.Drawing.Imaging.Encoder.SaveFlag;
            compressionEncoder = System.Drawing.Imaging.Encoder.Compression;

            SaveEncodeParam        = new System.Drawing.Imaging.EncoderParameter(saveEncoder, (long)System.Drawing.Imaging.EncoderValue.MultiFrame);
            CompressionEncodeParam = new System.Drawing.Imaging.EncoderParameter(compressionEncoder, (long)System.Drawing.Imaging.EncoderValue.CompressionCCITT4);
            EncoderParams.Param[0] = CompressionEncodeParam;
            EncoderParams.Param[1] = SaveEncodeParam;

            bitMaps[0].Save(this.m_FileName, codecInfo, EncoderParams);

            for (int i = 1; i < bitMaps.Count; i++)
            {
                if (bitMaps[i] == null)
                {
                    break;
                }

                SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionPage);
                CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionCCITT4);
                EncoderParams.Param[0] = CompressionEncodeParam;
                EncoderParams.Param[1] = SaveEncodeParam;
                bitMaps[0].SaveAdd(bitMaps[i], EncoderParams);
            }

            SaveEncodeParam        = new EncoderParameter(saveEncoder, (long)EncoderValue.Flush);
            EncoderParams.Param[0] = SaveEncodeParam;
            bitMaps[0].SaveAdd(EncoderParams);
        }
Ejemplo n.º 48
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();
                }
            }
        }
Ejemplo n.º 49
0
    public string LoadFacebookImage(string imglink, string imgext)
    {
        string savedpath = "";

        try
        {
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imglink);
            //  HttpPostedFile postedFile =// context.Request.Files["Filedata"];

            string RawTempPath = "images/tempFile";
            string tempPath    = MapPath(RawTempPath);
            string filetype    = "image";
            string dimension   = "200x200,100x100,405x405";
            System.Drawing.Bitmap    bmp;
            System.Drawing.Graphics  gr;
            System.Drawing.Rectangle rectDestination;
            // check if directory exists
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }

            string newimglink = imglink.Substring(imglink.LastIndexOf("/") + 1);
            newimglink = newimglink.Substring(0, newimglink.LastIndexOf("."));
            string filename = newimglink + Guid.NewGuid().ToString().Substring(0, 6) + imgext;

            save_file_from_url(tempPath + @"\" + filename, imglink);
            //postedFile.SaveAs(tempPath + @"\" + filename);
            savedpath = RawTempPath + "/" + filename;

            if (filetype == "image" && !string.IsNullOrEmpty(dimension))
            {
                string[] splitter = { "--" };

                int    thumbWidth    = 0;
                int    thumbHeight   = 0;
                int    filecount     = 0;
                string fileExtension = System.IO.Path.GetExtension(savedpath).ToLower();
                // check if image
                bool isImage = false;
                if (imglink.Substring(imglink.LastIndexOf(".")).ToLower() == ".jpeg" || imglink.Substring(imglink.LastIndexOf(".")).ToLower() == ".jpg" || imglink.Substring(imglink.LastIndexOf(".")).ToLower() == ".png" || imglink.Substring(imglink.LastIndexOf(".")).ToLower() == ".gif")
                {
                    isImage = true;
                }

                if (isImage)
                {
                    string[] dimarr = dimension.Split(',');
                    foreach (string dim in dimarr)
                    {
                        string[] imageSize = dim.Split('x');
                        thumbWidth  = int.Parse(imageSize[0]);
                        thumbHeight = int.Parse(imageSize[1]);
                        int srcWidth  = 0;
                        int srcHeight = 0;
                        System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(tempPath + @"\" + filename);
                        srcWidth  = fullSizeImg.Width;
                        srcHeight = fullSizeImg.Height;

                        if ((srcHeight * 1000 / thumbHeight) > (srcWidth * 1000 / thumbWidth))
                        {
                            thumbHeight = (srcHeight * thumbWidth) / srcWidth;
                        }
                        else
                        {
                            thumbWidth = (srcWidth * thumbHeight) / srcHeight;
                        }
                        bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                        gr  = System.Drawing.Graphics.FromImage(bmp);
                        gr.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        gr.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                        rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
                        gr.DrawImage(fullSizeImg, rectDestination, 0, 0, srcWidth, srcHeight, System.Drawing.GraphicsUnit.Pixel);

                        savedpath = savedpath.Replace(fileExtension, "");
                        System.Drawing.Imaging.Encoder           quality     = System.Drawing.Imaging.Encoder.Quality;
                        System.Drawing.Imaging.EncoderParameter  ratio       = new System.Drawing.Imaging.EncoderParameter(quality, 80L);
                        System.Drawing.Imaging.EncoderParameters codecParams = new System.Drawing.Imaging.EncoderParameters(1);
                        codecParams.Param[0] = ratio;
                        switch (fileExtension)
                        {
                        case ".jpg":
                            bmp.Save(Server.MapPath(savedpath + "_size" + filecount + fileExtension), GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg), codecParams);
                            break;

                        case ".gif":
                            bmp.Save(Server.MapPath(savedpath + "_size" + filecount + fileExtension), GetEncoder(System.Drawing.Imaging.ImageFormat.Gif), codecParams);
                            break;

                        case ".png":
                            bmp.Save(Server.MapPath(savedpath + "_size" + filecount + fileExtension), GetEncoder(System.Drawing.Imaging.ImageFormat.Png), codecParams);
                            break;
                        }
                        filecount++;
                    }
                    savedpath = savedpath + "_size0" + fileExtension;
                }
            }
        }
        catch (Exception ex)
        {
            string aaa = ex.Message;
        }
        return(savedpath);
    }
Ejemplo n.º 50
0
        public static void GetThumb(Image originalImage, int width, int height, string outputPath)
        {
            int x, y, w, h;

            if (originalImage.Width > width && originalImage.Height > height)
            {
                w = width;
                h = width * originalImage.Height / originalImage.Width;
                if (h > height)
                {
                    h = height;
                    w = height * originalImage.Width / originalImage.Height;
                    x = (width - w) / 2;
                    y = 0;
                }
                else
                {
                    x = 0;
                    y = (height - h) / 2;
                }
            }
            else if (originalImage.Width > width)
            {
                w = width;
                h = width * originalImage.Height / originalImage.Width;
                x = 0;
                y = (height - h) / 2;
            }
            else if (originalImage.Height > height)
            {
                h = height;
                w = height * originalImage.Width / originalImage.Height;
                x = (width - w) / 2;
                y = 0;
            }
            else
            {
                w = originalImage.Width;
                h = originalImage.Height;
                x = (width - w) / 2;
                y = (height - h) / 2;
            }
            Bitmap   bm = new Bitmap(width, height);
            Graphics g  = Graphics.FromImage(bm);

            // 指定高质量、低速度呈现。
            g.SmoothingMode = SmoothingMode.HighQuality;
            // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.Clear(Color.White);
            g.DrawImage(originalImage, new Rectangle(x, y, w, h), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel);

            long[] quality = new long[1];
            quality[0] = 100;

            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            System.Drawing.Imaging.EncoderParameter  encoderParam  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo   jpegICI  = null;

            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[i];//设置JPEG编码
                    break;
                }
            }
            if (jpegICI != null)
            {
                bm.Save(outputPath, jpegICI, encoderParams);
            }

            bm.Dispose();
            originalImage.Dispose();
            g.Dispose();
        }
Ejemplo n.º 51
0
            /// <summary>
            /// Fills the given serialization context with this object
            /// </summary>
            /// <param name="info">The field information for the class</param>
            /// <param name="context">The stream containing the serialized object</param>
            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                //Add key
                info.AddValue("key", this.key);
                //Add image in a special way
                byte[] bits = null;

                // The Image class is not capable of multithreaded access.
                // Simultaneous access will throw a
                //    "InvalidOperationException: The object is currently in use elsewhere."
                // So it needs to be locked, and also locked anywhere else the Image is accessed
                // (such as in ImageSheetRenderer.Paint).
                using (Synchronizer.Lock(this.m_image)) {
                    if (this.m_image.RawFormat.Guid == ImageFormat.Emf.Guid)
                    {
                        info.AddValue("type", "emf");
                        Metafile mf  = (Metafile)((Metafile)this.m_image).Clone();
                        IntPtr   ptr = mf.GetHenhmetafile();
                        Debug.Assert(ptr != IntPtr.Zero, "Failed to get pointer to image.");
                        uint size = GetEnhMetaFileBits(ptr, 0, null);
                        bits = new byte[size];
                        uint numBits = GetEnhMetaFileBits(ptr, size, bits);
                        mf.Dispose();
                        Debug.Assert(size == numBits, "Improper serialization of metafile!");
                    }
                    else if (this.m_image.RawFormat.Guid == ImageFormat.Wmf.Guid)
                    {
                        info.AddValue("type", "wmf");
                        Metafile mf  = (Metafile)((Metafile)this.m_image).Clone();
                        IntPtr   ptr = mf.GetHenhmetafile();
                        Debug.Assert(ptr != IntPtr.Zero, "Failed to get pointer to image.");
                        uint size = GetMetaFileBitsEx(ptr, 0, null);
                        bits = new byte[size];
                        uint numBits = GetMetaFileBitsEx(ptr, size, bits);
                        mf.Dispose();
                        Debug.Assert(size == numBits, "Improper serialization of metafile!");
                    }
                    else if (this.m_image.RawFormat.Guid == ImageFormat.Png.Guid)
                    {
                        info.AddValue("type", "png");
                        System.IO.MemoryStream ms = new System.IO.MemoryStream(100000);
                        this.m_image.Save(ms, ImageFormat.Png);
                        bits = ms.ToArray();
                    }
                    else if (this.m_image.RawFormat.Guid == ImageFormat.Jpeg.Guid)
                    {
                        info.AddValue("type", "Jpeg");
                        System.IO.MemoryStream ms = new System.IO.MemoryStream();
                        long[] quality            = new long[1];
                        quality[0] = 100;
                        System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                        System.Drawing.Imaging.EncoderParameter  encoderParam  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                        encoderParams.Param[0] = encoderParam;
                        ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                        ImageCodecInfo   jpegICI  = null;
                        for (int x = 0; x < arrayICI.Length; x++)
                        {
                            if (arrayICI[x].FormatDescription.Equals("JPEG"))
                            {
                                jpegICI = arrayICI[x];
                                break;
                            }
                        }
                        if (jpegICI != null)
                        {
                            this.m_image.Save(ms, jpegICI, encoderParams);
                        }

                        bits = ms.ToArray();
                    }
                    else
                    {
                        info.AddValue("type", "png");
                        System.IO.MemoryStream ms = new System.IO.MemoryStream(100000);
                        this.m_image.Save(ms, ImageFormat.Png);
                        bits = ms.ToArray();
                    }
                }
                info.AddValue("image", bits);
            }
Ejemplo n.º 52
0
 public static void SendSmallImage(string fileName, string newFile, int maxHeight, int maxWidth)
 {
     System.Drawing.Image    image    = null;
     System.Drawing.Bitmap   bitmap   = null;
     System.Drawing.Graphics graphics = null;
     try
     {
         image = System.Drawing.Image.FromFile(fileName);
         System.Drawing.Imaging.ImageFormat rawFormat = image.RawFormat;
         System.Drawing.Size size = PIC.NewSize(maxWidth, maxHeight, image.Width, image.Height);
         bitmap   = new System.Drawing.Bitmap(size.Width, size.Height);
         graphics = System.Drawing.Graphics.FromImage(bitmap);
         graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
         graphics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
         graphics.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
         graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, size.Width, size.Height), 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
         if (graphics != null)
         {
             graphics.Dispose();
         }
         System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters();
         long[] value = new long[]
         {
             100L
         };
         System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, value);
         encoderParameters.Param[0] = encoderParameter;
         System.Drawing.Imaging.ImageCodecInfo[] imageEncoders  = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
         System.Drawing.Imaging.ImageCodecInfo   imageCodecInfo = null;
         for (int i = 0; i < imageEncoders.Length; i++)
         {
             if (imageEncoders[i].FormatDescription.Equals("JPEG"))
             {
                 imageCodecInfo = imageEncoders[i];
                 break;
             }
         }
         if (imageCodecInfo != null)
         {
             bitmap.Save(newFile, imageCodecInfo, encoderParameters);
         }
         else
         {
             bitmap.Save(newFile, rawFormat);
         }
     }
     catch
     {
     }
     finally
     {
         if (graphics != null)
         {
             graphics.Dispose();
         }
         if (image != null)
         {
             image.Dispose();
         }
         if (bitmap != null)
         {
             bitmap.Dispose();
         }
     }
 }
Ejemplo n.º 53
0
        public System.IO.MemoryStream AddImageSignPic(System.Drawing.Image img, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            System.Drawing.Graphics graphics = null;
            System.Drawing.Image    image    = null;
            System.Drawing.Imaging.ImageAttributes imageAttributes = null;
            System.IO.MemoryStream result;
            try
            {
                graphics        = System.Drawing.Graphics.FromImage(img);
                image           = new System.Drawing.Bitmap(watermarkFilename);
                imageAttributes = new System.Drawing.Imaging.ImageAttributes();
                System.Drawing.Imaging.ColorMap[] map = new System.Drawing.Imaging.ColorMap[]
                {
                    new System.Drawing.Imaging.ColorMap
                    {
                        OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0),
                        NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0)
                    }
                };
                imageAttributes.SetRemapTable(map, System.Drawing.Imaging.ColorAdjustType.Bitmap);
                float num = 0.5f;
                if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
                {
                    num = (float)watermarkTransparency / 10f;
                }
                float[][] array    = new float[5][];
                float[][] arg_A1_0 = array;
                int       arg_A1_1 = 0;
                float[]   array2   = new float[5];
                array2[0]          = 1f;
                arg_A1_0[arg_A1_1] = array2;
                float[][] arg_B8_0 = array;
                int       arg_B8_1 = 1;
                float[]   array3   = new float[5];
                array3[1]          = 1f;
                arg_B8_0[arg_B8_1] = array3;
                float[][] arg_CF_0 = array;
                int       arg_CF_1 = 2;
                float[]   array4   = new float[5];
                array4[2]          = 1f;
                arg_CF_0[arg_CF_1] = array4;
                float[][] arg_E3_0 = array;
                int       arg_E3_1 = 3;
                float[]   array5   = new float[5];
                array5[3]          = num;
                arg_E3_0[arg_E3_1] = array5;
                array[4]           = new float[]
                {
                    0f,
                    0f,
                    0f,
                    0f,
                    1f
                };
                float[][] newColorMatrix = array;
                System.Drawing.Imaging.ColorMatrix newColorMatrix2 = new System.Drawing.Imaging.ColorMatrix(newColorMatrix);
                imageAttributes.SetColorMatrix(newColorMatrix2, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);
                int x = 0;
                int y = 0;
                switch (watermarkStatus)
                {
                case 1:
                    x = (int)((float)img.Width * 0.01f);
                    y = (int)((float)img.Height * 0.01f);
                    break;

                case 2:
                    x = (int)((float)img.Width * 0.5f - (float)(image.Width / 2));
                    y = (int)((float)img.Height * 0.01f);
                    break;

                case 3:
                    x = (int)((float)img.Width * 0.99f - (float)image.Width);
                    y = (int)((float)img.Height * 0.01f);
                    break;

                case 4:
                    x = (int)((float)img.Width * 0.01f);
                    y = (int)((float)img.Height * 0.5f - (float)(image.Height / 2));
                    break;

                case 5:
                    x = (int)((float)img.Width * 0.5f - (float)(image.Width / 2));
                    y = (int)((float)img.Height * 0.5f - (float)(image.Height / 2));
                    break;

                case 6:
                    x = (int)((float)img.Width * 0.99f - (float)image.Width);
                    y = (int)((float)img.Height * 0.5f - (float)(image.Height / 2));
                    break;

                case 7:
                    x = (int)((float)img.Width * 0.01f);
                    y = (int)((float)img.Height * 0.99f - (float)image.Height);
                    break;

                case 8:
                    x = (int)((float)img.Width * 0.5f - (float)(image.Width / 2));
                    y = (int)((float)img.Height * 0.99f - (float)image.Height);
                    break;

                case 9:
                    x = (int)((float)img.Width * 0.99f - (float)image.Width);
                    y = (int)((float)img.Height * 0.99f - (float)image.Height);
                    break;
                }
                graphics.DrawImage(image, new System.Drawing.Rectangle(x, y, image.Width, image.Height), 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes);
                System.Drawing.Imaging.ImageCodecInfo[] imageEncoders  = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
                System.Drawing.Imaging.ImageCodecInfo   imageCodecInfo = null;
                System.Drawing.Imaging.ImageCodecInfo[] array6         = imageEncoders;
                for (int i = 0; i < array6.Length; i++)
                {
                    System.Drawing.Imaging.ImageCodecInfo imageCodecInfo2 = array6[i];
                    if (imageCodecInfo2.MimeType.IndexOf("jpeg") > -1)
                    {
                        imageCodecInfo = imageCodecInfo2;
                    }
                }
                System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters();
                long[] array7 = new long[1];
                if (quality < 0 || quality > 100)
                {
                    quality = 80;
                }
                array7[0] = (long)quality;
                System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, array7);
                encoderParameters.Param[0] = encoderParameter;
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                if (imageCodecInfo != null)
                {
                    img.Save(memoryStream, imageCodecInfo, encoderParameters);
                }
                result = memoryStream;
            }
            catch
            {
                System.IO.MemoryStream memoryStream = null;
                result = memoryStream;
            }
            finally
            {
                if (graphics != null)
                {
                    graphics.Dispose();
                }
                if (img != null)
                {
                    img.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
                if (imageAttributes != null)
                {
                    imageAttributes.Dispose();
                }
            }
            return(result);
        }
Ejemplo n.º 54
0
        public static ImageSize GetThumbnailImage(Image originalImage, string outname, float width, float height, Thumbnail Thumbnailmode)
        {
            float x = 0;
            float y = 0;
            float w = originalImage.Width;
            float h = originalImage.Height;

            #region A
            //if (originalImage.Width > width && originalImage.Height > height)
            //{
            //    if (originalImage.Width > originalImage.Height)
            //    {
            //        w = width;
            //        h = width * originalImage.Height / originalImage.Width;
            //        x = 0;
            //        y = (height - h) / 2;
            //        if (h > height)
            //        {
            //            h = height;
            //            w = height * originalImage.Width / originalImage.Height;
            //            x = (width - w) / 2;
            //            y = 0;
            //        }
            //    }
            //    else
            //    {
            //        h = height;
            //        w = height * (float)originalImage.Width / (float)originalImage.Height;
            //        x = (width - w) / 2;
            //        y = 0;
            //        if (w > width)
            //        {
            //            w = width;
            //            h = width * (float)originalImage.Height / (float)originalImage.Width;
            //            x = 0;
            //            y = (height - h) / 2;
            //        }
            //    }
            //}
            //else if ((float)originalImage.Width > width)
            //{
            //    w = width;
            //    h = width * (float)originalImage.Height / (float)originalImage.Width;
            //    x = 0;
            //    y = (height - h) / 2;
            //}
            //else if ((float)originalImage.Height > height)
            //{
            //    h = height;
            //    w = height * (float)originalImage.Width / (float)originalImage.Height;
            //    x =  (width - w) / 2;
            //    y = 0;
            //}
            //else
            //{
            //    w = (float)originalImage.Width;
            //    h = (float)originalImage.Height;
            //    x =  (width - w) / 2;
            //    y =  (height - h) / 2;
            //}
            //if (auto)
            //{
            //    x = 0;
            //    y = 0;
            //}
            #endregion

            switch (Thumbnailmode)
            {
            case Thumbnail.HW:
                break;

            case Thumbnail.W:
                height = originalImage.Height * width / originalImage.Width;
                break;

            case Thumbnail.H:
                width = originalImage.Width * height / originalImage.Height;
                break;

            case Thumbnail.Cut:
                if ((double)originalImage.Width / (double)originalImage.Height > (double)width / (double)width)
                {
                    h = originalImage.Height;
                    w = originalImage.Height * width / height;
                    y = 0;
                    x = (originalImage.Width - w) / 2;
                }
                else
                {
                    w = originalImage.Width;
                    h = originalImage.Width * height / width;
                    x = 0;
                    y = (originalImage.Height - h) * 0.382f;
                }
                break;

            case Thumbnail.AutoWH:
                if ((double)originalImage.Width / (double)originalImage.Height < (double)width / (double)width)
                {
                    h = originalImage.Height;
                    w = originalImage.Height * width / height;
                    y = (originalImage.Height - h) / 2;
                    x = (originalImage.Width - w) / 2;
                }
                else
                {
                    w = originalImage.Width;
                    h = originalImage.Width * height / width;
                    x = (originalImage.Width - w) / 2;
                    y = (originalImage.Height - h) / 2;
                }
                break;

            case Thumbnail.Auto:
                if (originalImage.Width < width && originalImage.Height < height)
                {
                    width  = originalImage.Width;
                    height = originalImage.Height;
                }
                else if (originalImage.Width < width && originalImage.Height > height)
                {
                    height = originalImage.Height * width / originalImage.Width;
                }
                else if (originalImage.Height < height && originalImage.Width > width)
                {
                    width = originalImage.Width * height / originalImage.Height;
                }
                else
                {
                    if (originalImage.Width > originalImage.Height)
                    {
                        height = originalImage.Height * width / originalImage.Width;
                    }
                    else
                    {
                        width = originalImage.Width * height / originalImage.Height;
                    }
                }
                break;

            default:
                break;
            }
            Bitmap   bm = new Bitmap((int)width, (int)height);
            Graphics g  = Graphics.FromImage(bm);
            g.SmoothingMode     = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.Clear(Color.White);
            //g.DrawImage(originalImage, new Rectangle((int)x, (int)y, (int)w, (int)h), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel);
            g.DrawImage(originalImage, new Rectangle(0, 0, (int)width, (int)height), new Rectangle((int)x, (int)y, (int)w, (int)h), GraphicsUnit.Pixel);
            long[] quality = new long[1];
            quality[0] = 100;
            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            System.Drawing.Imaging.EncoderParameter  encoderParam  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   jpegICI  = null;

            string fd = outname.Substring(outname.LastIndexOf('.')).ToLower().TrimStart('.');
            fd = fd == "jpg" ? "JPEG" : fd == "gif" ? "GIF" : fd.ToUpper();

            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals(fd))
                {
                    jpegICI = arrayICI[i];
                    break;
                }
            }
            if (jpegICI != null)
            {
                System.IO.File.Delete(outname);
                bm.Save(outname, jpegICI, encoderParams);
            }

            bm.Dispose();
            originalImage.Dispose();
            g.Dispose();
            return(new ImageSize()
            {
                width = width, height = height
            });
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Zoom image.
        /// </summary>
        /// <param name="imgSource">image byte array.</param>
        /// <param name="ifHeightOrWidth">base on height or width.if 1 the new image height equals size,otherwise the new image width equals size.</param>
        /// <param name="size">the new width or height value.</param>
        /// <param name="flag">the new iamge quality value.</param>
        /// <returns></returns>
        public static byte[] ZoomImage(byte[] imgSource, int ifHeightOrWidth = 1, int size = 100, int quality = 40)
        {
            try
            {
                MemoryStream         stream = new MemoryStream(imgSource);
                System.Drawing.Image sourImage = System.Drawing.Image.FromStream(stream);
                ImageFormat          tFormat = sourImage.RawFormat;
                int width = 0, height = 0;
                //按比例缩放
                int sourWidth  = sourImage.Width;
                int sourHeight = sourImage.Height;

                //以高为准,等比缩放
                if (ifHeightOrWidth == 1)
                {
                    height = size;
                    width  = height * sourWidth / sourHeight;
                }
                //以宽为准 等比缩放
                else
                {
                    width  = size;
                    height = width * sourHeight / sourWidth;
                }

                //缩放
                Bitmap   destBitmap = new Bitmap(width, height);
                Graphics g     = Graphics.FromImage(destBitmap);
                g.Clear(Color.Transparent);
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(sourImage, new Rectangle(0, 0, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
                g.Dispose();

                //压缩
                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                long[] qualityArray = new long[1];
                qualityArray[0] = quality;
                System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityArray);
                encoderParams.Param[0] = encoderParam;

                ImageCodecInfo[] arrayICI    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }

                MemoryStream outSm = new MemoryStream();
                if (jpegICIinfo != null)
                {
                    destBitmap.Save(outSm, jpegICIinfo, encoderParams);
                }
                else
                {
                    destBitmap.Save(outSm, tFormat);
                }
                sourImage.Dispose();
                var s = outSm.GetBuffer().Length;
                return(outSm.GetBuffer());
            }
            catch
            {
                return(imgSource);
            }
        }
Ejemplo n.º 56
0
        public FileInfo ResizeImageFile(FileInfo image, Options options, AsyncCodeActivityContext context)
        {
            // Get the image codec info
            ImageCodecInfo CodecInfo = GetEncoderInfo("image/jpeg");

            //Save the bitmap as a JPEG file with quality level 75.
            System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameter  encoderParameter     = new System.Drawing.Imaging.EncoderParameter(encoder, 100L);
            EncoderParameters encoderParameters    = new EncoderParameters();

            encoderParameters.Param[0] = encoderParameter;

            System.Drawing.Image  img    = null;
            System.Drawing.Bitmap bitmap = null;
            string savePath = string.Empty;

            try
            {
                img = System.Drawing.Image.FromFile(image.FullName);

                if (options.AutoRotate == true)
                {
                    var pi = img.PropertyItems.FirstOrDefault(p => p.Id == 0x0112);
                    if (pi != null)
                    {
                        switch (pi.Value[0])
                        {
                        case 6:
                            img.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                            break;

                        case 8:
                            img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                            break;

                        default:
                            break;
                        }
                    }
                }

                //set the width and height, using the original values if not specified
                int width  = options.Width == 0 ? img.Width : options.Width;
                int height = options.Height == 0 ? img.Height : options.Height;

                if (img.Width < img.Height)
                {
                    int tempWidth = width;
                    width  = height;
                    height = tempWidth;
                }

                bitmap = new System.Drawing.Bitmap(img, new System.Drawing.Size(width, height));

                //make sure the target directory exists. If not, create it!
                if (!Directory.Exists(options.TargetDirectory))
                {
                    Directory.CreateDirectory(options.TargetDirectory);
                }

                savePath = Path.Combine(options.TargetDirectory, image.Name);
                bitmap.Save(savePath, CodecInfo, encoderParameters);

                if (!string.IsNullOrWhiteSpace(savePath))
                {
                    return(new FileInfo(savePath));
                }

                return(null);
            }
            catch
            {
                throw new Exception
                      (
                          string.Format("Cannot resize '{0} as it is not a valid image file!", image.Name)
                      );
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }

                if (img != null)
                {
                    img.Dispose();
                }
            }
        }
Ejemplo n.º 57
0
        public void ProcessRequest(HttpContext context)
        {
            string imgUrl = context.Request.QueryString["img"];
            int    width  = context.Request.QueryString["w"] != null?int.Parse(context.Request.QueryString["w"]) : 0;

            int height = context.Request.QueryString["h"] != null?int.Parse(context.Request.QueryString["h"]) : 0;

            bool square = context.Request.QueryString["s"] != null ? true : false;

            string key = "img_" + imgUrl + "_" + width.ToString() + "_" + height.ToString() + "_" + square.ToString();

            Cache cache = System.Web.HttpContext.Current.Cache;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            if (cache[key] == null)
            {
                Image  image   = null;
                string imgPath = context.Server.MapPath(imgUrl);
                image = Image.FromFile(imgPath);

                int _width  = image.Size.Width;
                int _height = image.Size.Height;

                if (height == 0)
                {
                    double _zoom_factor = (double)_width / width;
                    height = Convert.ToInt32(_height / _zoom_factor);
                }
                else if (width == 0)
                {
                    double _zoom_factor = (double)_height / height;
                    width = Convert.ToInt32(_width / _zoom_factor);
                }
                else
                {
                    double _zoom_factor = (double)_width / width;
                    if (_height / height > _zoom_factor)
                    {
                        _zoom_factor = (double)_height / height;
                    }
                    width  = Convert.ToInt32(_width / _zoom_factor);
                    height = Convert.ToInt32(_height / _zoom_factor);
                }

                if (width == 0 && height == 0)
                {
                    width  = _width;
                    height = _height;
                }

                if (square)
                {
                    image = squareImage(image);
                    if (width < height)
                    {
                        width = height;
                    }
                    if (height < width)
                    {
                        height = width;
                    }
                }

                image = resizeImage(image, new Size(width, height));

                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                long[] quality = new long[1];

                quality[0] = 100; //0 to 100 最高质量为100
                System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;

                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
                ImageCodecInfo   jpegICI  = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[x];//设置JPEG编码
                        break;
                    }
                }
                image.Save(ms, jpegICI, encoderParams);

                cache.Insert(key, ms);
                image.Dispose();
            }
            else
            {
                ms = (System.IO.MemoryStream)cache[key];
            }

            context.Response.ClearContent();
            context.Response.ContentType = "image/jpeg";
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
            context.Response.Cache.SetMaxAge(new TimeSpan(DateTime.Now.AddDays(30).Ticks - DateTime.Now.Ticks));
            context.Response.BinaryWrite(ms.ToArray());
        }
Ejemplo n.º 58
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth  = width;
            int toheight = height;

            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
            case "HW":      //指定高宽缩放(可能变形)
                break;

            case "W":       //指定宽,高按比例
                toheight = originalImage.Height * width / originalImage.Width;
                break;

            case "H":       //指定高,宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;

            case "Cut":     //指定高宽裁减(不变形)
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

            try
            {
                long[] quality = new long[1];
                quality[0] = 100;

                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                System.Drawing.Imaging.EncoderParameter  encoderParam  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
                ImageCodecInfo   jpegICI  = null;
                for (int i = 0; i < arrayICI.Length; i++)
                {
                    if (arrayICI[i].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[i];//设置JPEG编码
                        break;
                    }
                }
                if (jpegICI != null)
                {
                    //bm.Save(Server.MapPath("upload/c.jpg"), jpegICI, encoderParams);
                    //以jpg格式保存缩略图
                    bitmap.Save(thumbnailPath, jpegICI, encoderParams);
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Ejemplo n.º 59
0
        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置:0=不使用 1=左上 2=中上 3=右上 4=左中 ... 9=右下</param>
        /// <param name="quality">是否是高质量图片 取值范围0--100</param>
        /// <param name="watermarkTransparency">图片水印透明度 取值范围1--10 (10为不透明)</param>

        public static void AddImageSignPic(string Path, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            System.Drawing.Image    img = System.Drawing.Image.FromFile(Path);
            System.Drawing.Graphics g   = System.Drawing.Graphics.FromImage(img);

            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            System.Drawing.Image watermark = new System.Drawing.Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();
            System.Drawing.Imaging.ColorMap        colorMap        = new System.Drawing.Imaging.ColorMap();

            colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0);
            System.Drawing.Imaging.ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }

            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes);

            System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            System.Drawing.Imaging.ImageCodecInfo   ici    = null;
            foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs)
            {
                //if (codec.MimeType.IndexOf("jpeg") > -1)
                if (codec.MimeType.Contains("jpeg"))
                {
                    ici = codec;
                }
            }
            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }
            qualityParam[0] = quality;

            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
Ejemplo n.º 60
0
    /// <summary>
    /// 压缩文件
    /// /// </summary>
    /// <param name="dir">文件目录</param>
    /// <param name="zipfilename">zip文件名</param>
    public void compressFiles(string[] filenames, string zipfilename)
    {
        //try
        //{

        //    using (ZipOutputStream s = new ZipOutputStream(File.Create(zipfilename)))
        //    {
        //        s.SetLevel(9); // 0 - store only to 9 - means best compression  压缩等级
        //        byte[] buffer = new byte[4096];
        //        foreach (string file in filenames)
        //        {
        //            string elDir = System.IO.Path.GetDirectoryName(file);
        //            string userName = System.Web.Configuration.WebConfigurationManager.AppSettings["el_share_authenticate_username"];
        //            string password = System.Web.Configuration.WebConfigurationManager.AppSettings["el_share_authenticate_password"];
        //            uint r = WNetConnectionHelper.WNetAddConnection(userName, password, elDir, null);
        //            ZipEntry entry = new ZipEntry(Path.GetFileName(file));
        //            entry.DateTime = DateTime.Now;
        //            s.PutNextEntry(entry);
        //            using (FileStream fs = File.OpenRead(file))
        //            {
        //                int sourceBytes;
        //                do
        //                {
        //                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
        //                    s.Write(buffer, 0, sourceBytes);
        //                } while (sourceBytes > 0);
        //            }
        //        }
        //        s.Finish();
        //        s.Close();
        //    }
        //}
        //catch(Exception EX)
        //{

        //}

        System.Drawing.Imaging.ImageCodecInfo    myImageCodecInfo;
        System.Drawing.Imaging.Encoder           myEncoder;
        System.Drawing.Imaging.EncoderParameter  myEncoderParameter;
        System.Drawing.Imaging.EncoderParameters myEncoderParameters;
        // Get an ImageCodecInfo object that represents the JPEG codec.
        myImageCodecInfo = GetEncoderInfo("image/jpeg");
        // Create an Encoder object based on the GUID
        // for the Quality parameter category.
        myEncoder = System.Drawing.Imaging.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 System.Drawing.Imaging.EncoderParameters(1);
        // Save the bitmap as a JPEG file with 给定的 quality level
        //压缩等级,0到100,0 最差质量,100 最佳</param>
        myEncoderParameter           = new System.Drawing.Imaging.EncoderParameter(myEncoder, 30L);
        myEncoderParameters.Param[0] = myEncoderParameter;
        try
        {
            using (ZipOutputStream s = new ZipOutputStream(File.Create(zipfilename)))
            {
                s.SetLevel(9);  // 0 - store only to 9 - means best compression  压缩等级
                foreach (string file in filenames)
                {
                    string elDir    = System.IO.Path.GetDirectoryName(file);
                    string userName = System.Web.Configuration.WebConfigurationManager.AppSettings["el_share_authenticate_username"];
                    string password = System.Web.Configuration.WebConfigurationManager.AppSettings["el_share_authenticate_password"];
                    uint   r        = WNetConnectionHelper.WNetAddConnection(userName, password, elDir, null);


                    ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                    entry.DateTime = DateTime.Now;
                    s.PutNextEntry(entry);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (System.Drawing.Image img = System.Drawing.Image.FromFile(file))
                        {
                            img.Save(ms, myImageCodecInfo, myEncoderParameters);
                            byte[] buffer          = ms.GetBuffer();
                            long   byteLength      = buffer.Length;
                            long   leftByterLength = byteLength;
                            int    startIndex      = 0;
                            int    wirteByteLength = 0;
                            while (leftByterLength > 0)
                            {
                                wirteByteLength = leftByterLength >= 4096 ? 4096 : (int)leftByterLength;
                                s.Write(buffer, startIndex, wirteByteLength);
                                leftByterLength = leftByterLength - wirteByteLength;
                                startIndex      = startIndex + wirteByteLength;
                            }
                        }
                    }
                    WNetConnectionHelper.WNetCancelConnection(userName, 1, true);
                }
                s.Finish();
                s.Close();
            }
        }
        catch (Exception EX)
        {
        }
    }