示例#1
0
        public Bitmap ResizeJpeg(Image sourcePhoto, int width, int height)
        {
            if (sourcePhoto == null)
            {
                throw new ArgumentNullException("sourcePhoto");
            }

            if (width <= 0)
            {
                throw new ArgumentException("Width must be greater than 0.");
            }

            if (height <= 0)
            {
                throw new ArgumentException("Height must be greater than 0.");
            }

            int sourceWidth = sourcePhoto.Width;
            int sourceHeight = sourcePhoto.Height;

            var destPhoto = new Bitmap(sourcePhoto, width, height);
            destPhoto.SetResolution(sourcePhoto.HorizontalResolution, sourcePhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(destPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.DrawImage(sourcePhoto, new Rectangle(0, 0, width, height), new Rectangle(0, 0, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
            grPhoto.Dispose();

            foreach (PropertyItem propertyItem in sourcePhoto.PropertyItems)
            {
                destPhoto.SetPropertyItem(propertyItem);
            }

            return destPhoto;
        }
示例#2
0
        /// <summary>
        /// Modifies an Profile image.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <param name="w">The w.</param>
        /// <param name="h">The h.</param>
        /// <param name="PersonID">Profile Image to work on</param>
        /// <returns>New Image Id</returns>
        private bool ModifyImage(int x, int y, int w, int h, Person person)
        {
            string ProfilDirSetting = ConfigurationManager.AppSettings["ProfileImage"];

            if (string.IsNullOrWhiteSpace(ProfilDirSetting))
            {
                throw new ArgumentNullException();
            }

            var ProfilBilled = string.Format(ProfilDirSetting, person.PersonID);

            if (System.IO.File.Exists(Server.MapPath(ProfilBilled)))
            {
                Image img = Image.FromFile(Server.MapPath(ProfilBilled));



                using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(428, 550))
                {
                    _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                    using (Graphics _graphic = Graphics.FromImage(_bitmap))
                    {
                        _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        _graphic.Clear(Color.White);
                        //_graphic.DrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, 428, 550), x, y, w, h, GraphicsUnit.Pixel);
                        //_graphic.DrawImage(img, new Rectangle(0, 0, w, h), x, y, w, h, GraphicsUnit.Pixel);
                        //_graphic.DrawImage(img, 0, 0, img.Width, img.Height);
                        //_graphic.DrawImage(img, new Rectangle(0, 0, 428, 550), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                    }
                    System.Drawing.Imaging.PropertyItem prop = img.PropertyItems[0];
                    SetProperty(ref prop, 270, string.Format("Username: {0}, {1}", person.UserName, person.FullName));
                    _bitmap.SetPropertyItem(prop);
                    SetProperty(ref prop, 33432, "Copyright Natteravnene www.natteravnene.dk");
                    _bitmap.SetPropertyItem(prop);
                    //TODO: Set more properties
                    img.Dispose();

                    _bitmap.Save(Server.MapPath(ProfilBilled), System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }

            return(true);
        }
示例#3
0
		public static Image LoadThumbnail(string filePath)
		{
			string thumbPath = GetThumbPath(filePath);
			using (Image image = Image.FromFile(thumbPath))
			{
				Image thumb = new Bitmap(image);
				thumb.SetPropertyItem(image.GetPropertyItem(18246));
				return thumb;
			}
		}
示例#4
0
        /// <summary>
        /// Resizes image to fit within the specified with and height, aspect ratio is maintained.
        /// </summary>
        /// <param name="width">The maximum width the image has to fit within, set to null to not restrict width.</param>
        /// <param name="height">The maximum height the image has to fit within, set to null to not restrict height.</param>
        /// <returns>A reference to this object to allow chaining operations together.</returns>
        public ImageMedia Resize(int? width, int? height)
        {
            if (width == null && height == null || width == 0 && height == 0)
                return this;

            int w = (width == null || width == 0) ? _source.Width : width.Value;
            int h = (height == null || height == 0) ? _source.Height : height.Value;
            float desiredRatio = (float)w / h;
            float scale, posx, posy;
            float ratio = (float)_source.Width / _source.Height;

            if (_source.Width < w && _source.Height < h)
            {
                scale = 1f;
                posy = (h - _source.Height) / 2f;
                posx = (w - _source.Width) / 2f;
            }
            else if (ratio > desiredRatio)
            {
                scale = (float)w / _source.Width;
                posy = (h - (_source.Height * scale)) / 2f;
                posx = 0f;
            }
            else
            {
                scale = (float)h / _source.Height;
                posx = (w - (_source.Width * scale)) / 2f;
                posy = 0f;
            }

            //if (!background.HasValue)
            //{
            w = (int)(_source.Width * scale);
            h = (int)(_source.Height * scale);
            posx = 0f;
            posy = 0f;
            //}

            Image resizedImage = new Bitmap(w, h);
            Graphics g = Graphics.FromImage(resizedImage);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawImage(_source, posx, posy, _source.Width * scale, _source.Height * scale);

            foreach (PropertyItem item in _source.PropertyItems)
                resizedImage.SetPropertyItem(item);

            _source = resizedImage;
            _data = null;
            return this;
        }
示例#5
0
 protected override string EncodingAlgorithm(string src, ISecretMessage message)
 {
     var tmp = FileManager.CopyImageToTmp(src);
     using (var bmp = new Bitmap(src))
     {
         var item = bmp.PropertyItems.OrderByDescending(x => x.Id).First();
         item.Id = item.Id + 1;
         item.Len = Bytes.Length;
         item.Value = Bytes;
         item.Type = 1;
         bmp.SetPropertyItem(item);
         bmp.Save(tmp);
     }
     return tmp;
 }
示例#6
0
文件: Form1.cs 项目: Hagser/csharp
 private void LoadFiles(string[] files)
 {
     foreach (string file in files)
     {
         if (Directory.Exists(file))
         {
             LoadFiles(Directory.EnumerateFiles(file).ToArray());
         }
         else
         {
             try
             {
                 FileInfo fi = new FileInfo(file);
                 if (fi.Extension.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase))
                 {
                     DateTime dtlw = fi.LastWriteTime;
                     DateTime dtct = fi.CreationTime;
                     using (Image img = Bitmap.FromFile(file))
                     {
                         System.GC.Collect();
                         using (Image Image = new Bitmap(Bitmap.FromFile(fi.FullName) as Image, int.Parse(Math.Floor(img.Width * .5).ToString()), int.Parse(Math.Floor(img.Height * .5).ToString())))
                         {
                             string strFilename = strFolder != "" ? strFolder + "\\" + fi.Name : fi.FullName;
                             foreach (PropertyItem pi in img.PropertyItems)
                             {
                                 Image.SetPropertyItem(pi);
                             }
                             Image.Save(strFilename, ImageFormat.Jpeg);
                             FileInfo finew = new FileInfo(strFilename);
                             finew.LastWriteTime = dtlw;
                             finew.CreationTime = dtct;
                             idone++;
                             this.Invoke((MethodInvoker)delegate { label1.Text = idone.ToString(); });
                         }
                     }
                 }
             }
             catch { }
         }
     }
 }
        /// <summary>
        /// Creates a deep copy of an image allowing you to set the pixel format.
        /// Disposing of the original is the responsibility of the user.
        /// <remarks>
        /// Unlike the native <see cref="Image.Clone"/> method this also copies animation frames.
        /// </remarks>
        /// </summary>
        /// <param name="source">The source image to copy.</param>
        /// <param name="animationProcessMode">The process mode for frames in animated images.</param>
        /// <param name="format">The <see cref="PixelFormat"/> to set the copied image to.</param>
        /// <param name="preserveExifData">Whether to preserve exif metadata. Defaults to false.</param>
        /// <returns>
        /// The <see cref="Image"/>.
        /// </returns>
        public static Image Copy(this Image source, AnimationProcessMode animationProcessMode, PixelFormat format = PixelFormat.Format32bppPArgb, bool preserveExifData = false)
        {
            if (source.RawFormat.Equals(ImageFormat.Gif))
            {
                // Read from the correct first frame when performing additional processing
                source.SelectActiveFrame(FrameDimension.Time, 0);
                GifDecoder decoder = new GifDecoder(source, animationProcessMode);
                GifEncoder encoder = new GifEncoder(null, null, decoder.LoopCount);

                // Have to use Octree here, there's no way to inject it.
                OctreeQuantizer quantizer = new OctreeQuantizer();
                for (int i = 0; i < decoder.FrameCount; i++)
                {
                    GifFrame frame = decoder.GetFrame(source, i);
                    frame.Image = quantizer.Quantize(((Bitmap)frame.Image).Clone(new Rectangle(0, 0, frame.Image.Width, frame.Image.Height), format));
                    ((Bitmap)frame.Image).SetResolution(source.HorizontalResolution, source.VerticalResolution);
                    encoder.AddFrame(frame);
                }

                return encoder.Save();
            }

            // Create a new image and copy it's pixels.
            Bitmap copy = new Bitmap(source.Width, source.Height, format);
            copy.SetResolution(source.HorizontalResolution, source.VerticalResolution);
            using (Graphics graphics = Graphics.FromImage(copy))
            {
                graphics.DrawImageUnscaled(source, 0, 0);
            }

            if (preserveExifData)
            {
                foreach (PropertyItem item in source.PropertyItems)
                {
                    copy.SetPropertyItem(item);
                }
            }

            return copy;
        }
示例#8
0
        public static Bitmap Scale(Bitmap Bitmap, int width, int height)
        {
            Bitmap scaledBitmap = new Bitmap(width, height);

            // Scale the bitmap in high quality mode.
            using (Graphics gr = Graphics.FromImage(scaledBitmap))
            {
                gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                gr.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                gr.DrawImage(Bitmap, new Rectangle(0, 0, width, height), new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), GraphicsUnit.Pixel);
            }

            // Copy original Bitmap's EXIF tags to new bitmap.
            foreach (PropertyItem propertyItem in Bitmap.PropertyItems)
            {
                scaledBitmap.SetPropertyItem(propertyItem);
            }

            return scaledBitmap;
        }
        /// <summary>
        /// Scales a image using high quality mode.
        /// </summary>
        /// <param name="image">The image to scale.</param>
        /// <param name="scaleFactorX">Scale factor on the X axis.</param>
        /// <param name="scaleFactorY">Scale factor on the Y axis.</param>
        /// <returns>The scaled image.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="image"/> is <c>null</c>.</exception>
        public static Image ScaleBitmap(this Image image, float scaleFactorX, float scaleFactorY)
        {
            if (image == null)
            {
                throw new ArgumentNullException("image");
            }

            int scaledWidth = (int)System.Math.Max(image.Width * scaleFactorX, 1.0f);
            int scaledHeight = (int)System.Math.Max(image.Height * scaleFactorY, 1.0f);

            Image scaledImage = new Bitmap(scaledWidth, scaledHeight);

            using (Graphics graphics = Graphics.FromImage(scaledImage))
            {
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                graphics.DrawImage(image, new Rectangle(0, 0, scaledWidth, scaledHeight), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
            }

            foreach (PropertyItem propertyItem in image.PropertyItems)
            {
                scaledImage.SetPropertyItem(propertyItem);
            }

            return scaledImage;
        }
示例#10
0
        static void Main(string[] args)
        {
            Console.Title = "Shrink Images";
               Console.ForegroundColor = ConsoleColor.Red;
               Console.WriteLine("This program has no warranties or guarantees.");
               Console.WriteLine("This program is not responsible for any damages.");
               Console.WriteLine("");
               Console.ForegroundColor = ConsoleColor.White;

               float newWidth = 0;

               do
            {
                Console.WriteLine("Enter new image width:");
                try
                {
                    newWidth = (float)Int32.Parse(Console.ReadLine());
                    if ((int)newWidth < 10)
                        throw new Exception();
                }
                catch { newWidth = 0; }

            }while (0 == newWidth);

               //Get all the *.jpg files (pictures) in "." this directory
               DirectoryInfo di = new DirectoryInfo(".");
               FileInfo[] pictures = di.GetFiles("*.jpg");

               Image oldImage = null;
               Image shrunkImage = null;
               Graphics oGraphic = null;

               string directoryPath, newName;
               int smallHeight, smallWidth;

               float shrinkFactor;

               foreach (FileInfo fileinfo in pictures)
            {
                try
                {
                    oldImage = Image.FromFile(fileinfo.FullName);

                    if (oldImage.Width <= newWidth)
                    {
                        Console.WriteLine("Skipping " + fileinfo.Name + "...");
                        continue;// skip this image nothing to do already small
                    }

                    Console.WriteLine("Shrinking " + fileinfo.Name + "...");

                    if (oldImage.Height < oldImage.Width) //Landscape
                        shrinkFactor = oldImage.Width / newWidth;
                    else //Portrait;
                        shrinkFactor = oldImage.Height / newWidth;

                    smallHeight = (int)(oldImage.Height / shrinkFactor);
                    smallWidth = (int)(oldImage.Width / shrinkFactor);

                    //Create new (blank) Image object called "shrunkImage" of new smaller size (canvas)
                    shrunkImage = new Bitmap(smallWidth, smallHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                    //Create new Graphics object called "oGraphic" based on object "shrunkImage"
                    //with multiple quality attributes
                    oGraphic = Graphics.FromImage(shrunkImage);
                    oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                    oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                    oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    //Set attribute of object "oGraphic" to rectangle of new smaller size (photo on canvas)
                    Rectangle rect = new Rectangle(0, 0, smallWidth, smallHeight);

                    //Draw the old photo in the new rectangle
                    oGraphic.DrawImage(oldImage, rect);

                    //Copy over jpeg meta data
                    foreach (PropertyItem item in oldImage.PropertyItems)
                        shrunkImage.SetPropertyItem(item);

                    //Save as a JPEG
                    directoryPath = System.IO.Path.GetDirectoryName(fileinfo.FullName);
                    newName = directoryPath + "\\" + "s" + ((int)newWidth) + "-" + fileinfo.Name;
                    shrunkImage.Save(newName, ImageFormat.Jpeg);
                }
                catch (Exception exp)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failuer:" + exp.Message);
                    Console.ForegroundColor = ConsoleColor.White;
                }
                finally
                {
                    if(oldImage != null) oldImage.Dispose();
                    if (shrunkImage != null) shrunkImage.Dispose();
                    if (oGraphic != null) oGraphic.Dispose();
                }
             }

               Console.WriteLine("Operation complete. Press any key to close.");
               Console.ReadKey(true);
        }
示例#11
0
文件: SaveTo.cs 项目: seeseekey/CSCL
		public void SaveToJpeg(string filename, int exifWidth, int exifHeight)
		{
			if(channelFormat==Format.RGBA)
			{
				ConvertToRGB().SaveToJpeg(filename, exifWidth, exifHeight);
				return;
			}

			if(channelFormat!=Format.RGB) throw new Exception("Only rgb images can be saved by SaveToJpeg.");

			Bitmap bmp=new Bitmap((int)width, (int)height, PixelFormat.Format24bppRgb);

			BitmapData data=bmp.LockBits(new Rectangle(0, 0, (int)width, (int)height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

			if(((int)width*3)==data.Stride)
			{
				Marshal.Copy(imageData, 0, data.Scan0, (int)(width*height*3));
			}
			else
			{
				if(IntPtr.Size==4)
				{
					for(uint i=0; i<height; i++)
					{
						Marshal.Copy(imageData, (int)(width*3*i), (IntPtr)(data.Scan0.ToInt32()+(int)(i*data.Stride)), (int)(width*3));
					}
				}
				else if(IntPtr.Size==8)
				{
					for(uint i=0; i<height; i++)
					{
						Marshal.Copy(imageData, (int)(width*3*i), (IntPtr)(data.Scan0.ToInt64()+(long)(i*data.Stride)), (int)(width*3));
					}
				}
			}
			bmp.UnlockBits(data);
			data=null;

			if(exifWidth>0&&exifHeight>0)
			{
				PropertyItem o=(PropertyItem)Activator.CreateInstance(typeof(PropertyItem), true);

				byte[] buff=Encoding.ASCII.GetBytes("ASCII\0\0\0"+exifWidth+"x"+exifHeight);
				o.Id=0x9286;
				o.Type=7;
				o.Len=buff.Length;
				o.Value=buff;
				bmp.SetPropertyItem(o);

				o=(PropertyItem)Activator.CreateInstance(typeof(PropertyItem), true);
				o.Id=0x100;
				o.Type=4;
				o.Len=4;
				o.Value=BitConverter.GetBytes((uint)exifWidth);
				bmp.SetPropertyItem(o);

				o=(PropertyItem)Activator.CreateInstance(typeof(PropertyItem), true);
				o.Id=0x101;
				o.Type=4;
				o.Len=4;
				o.Value=BitConverter.GetBytes((uint)exifHeight);
				bmp.SetPropertyItem(o);
			}

			bmp.Save(filename, ImageFormat.Jpeg);
			bmp.Dispose();
			bmp=null;
		}
    public static bool Convert(string filename, int frameDelayMS, List <System.Drawing.Bitmap> Bitmaps)
    {
        var gifEncoder = GetEncoder(ImageFormat.Gif);
        // Params of the first frame.
        var encoderParams1 = new EncoderParameters(1);

        encoderParams1.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
        // Params of other frames.
        var encoderParamsN = new EncoderParameters(1);

        encoderParamsN.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.FrameDimensionTime);
        // Params for the finalizing call.
        var encoderParamsFlush = new EncoderParameters(1);

        encoderParamsFlush.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.Flush);

        // PropertyItem for the frame delay (apparently, no other way to create a fresh instance).
        var frameDelay = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));

        frameDelay.Id   = PropertyTagFrameDelay;
        frameDelay.Type = PropertyTagTypeLong;
        // Length of the value in bytes.
        frameDelay.Len = Bitmaps.Count * UintBytes;
        // The value is an array of 4-byte entries: one per frame.
        // Every entry is the frame delay in 1/100-s of a second, in little endian.
        frameDelay.Value = new byte[Bitmaps.Count * UintBytes];
        // E.g., here, we're setting the delay of every frame to 1 second.
        var frameDelayBytes = System.BitConverter.GetBytes((uint)frameDelayMS);

        for (int j = 0; j < Bitmaps.Count; ++j)
        {
            System.Array.Copy(frameDelayBytes, 0, frameDelay.Value, j * UintBytes, UintBytes);
        }

        // PropertyItem for the number of animation loops.
        var loopPropertyItem = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));

        loopPropertyItem.Id   = PropertyTagLoopCount;
        loopPropertyItem.Type = PropertyTagTypeShort;
        loopPropertyItem.Len  = 1;
        // 0 means to animate forever.
        loopPropertyItem.Value = System.BitConverter.GetBytes((ushort)0);

        using (var stream = new FileStream(filename + ".gif", FileMode.Create)) {
            bool first = true;
            System.Drawing.Bitmap firstBitmap = null;
            // Bitmaps is a collection of Bitmap instances that'll become gif frames.
            foreach (var bitmap in Bitmaps)
            {
                if (first)
                {
                    firstBitmap = bitmap;
                    firstBitmap.SetPropertyItem(frameDelay);
                    firstBitmap.SetPropertyItem(loopPropertyItem);
                    firstBitmap.Save(stream, gifEncoder, encoderParams1);
                    first = false;
                }
                else
                {
                    firstBitmap.SaveAdd(bitmap, encoderParamsN);
                }
            }
            firstBitmap.SaveAdd(encoderParamsFlush);
        }

        foreach (var bitmap in Bitmaps)
        {
            bitmap.Dispose();
        }

        UnityEditor.AssetDatabase.Refresh();

        return(true);
    }
示例#13
0
        private void CopyWithOffsetFiles(string from, string to, int hours, int minutes, int years, int months, int days)
        {
            string[] files = Directory.GetFiles(from);
            List<FileInfo> filesFI = files.Select(s => new FileInfo(s)).ToList();

            foreach (var file in filesFI)
            {
                string saveTO = to + "\\" + Guid.NewGuid().ToString();

                try
                {
                    Bitmap image = new Bitmap(file.FullName);
                    PropertyItem propItem = image.GetPropertyItem(36867);

                    string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
                    DateTime dt = DateTime.Parse(dateTaken);

                    //dt = dt.AddHours(11).AddMinutes(23).AddYears(7).AddMonths(5).AddDays(-6);
                    dt = dt.AddHours(hours).AddMinutes(minutes).AddYears(years).AddMonths(months).AddDays(days);

                    byte[] aa = Encoding.UTF8.GetBytes(dt.ToString("yyyy:MM:dd HH:mm:ss") + "\0");
                    propItem.Value = aa;

                    image.SetPropertyItem(propItem);

                    image.Save(saveTO);
                    image.Dispose();
                    //f.CopyTo(to + (counter < 10 ? "0" + counter : counter.ToString()) + ".jpg");
                }
                catch
                {
                    Invoke(new MethodInvoker(delegate
                    {
                        lblError.Text = "Произашла ошибка при добавленни сдвига во времени, файлы с ошибками помечены как ERROR_0700.jpg";
                    }));
                    file.CopyTo(saveTO + "_ERROR");
                }

                Invoke(new MethodInvoker(delegate
                {
                    lblProgress.Text = mainText + " " + (filesFI.IndexOf(file) + 1) + "/" + filesFI.Count;
                    progressBar1.Value = (int)((Convert.ToDouble((filesFI.IndexOf(file) + 1)) / Convert.ToDouble(filesFI.Count)) * 1000);
                }));
            }
        }
示例#14
0
        private void TestFunc1(string fileName)
        {
            Bitmap bmp = new Bitmap(fileName);

            foreach (System.Drawing.Imaging.PropertyItem p in bmp.PropertyItems)
            {
                // 0x9003 - 原画像データの生成日時
                // 0x9004 - デジタルデータの作成日時

                // 0x0001-北緯(N) or 南緯(S)(Ascii)
                // 0x0002-緯度(数値)(Rational)
                // 0x0003-東経(E) or 西経(W)(Ascii)
                // 0x0004-経度(数値)(Rational)
                // 0x0005-高度の基準(Byte)
                // 0x0006-高度(数値)(Rational)
                // 0x0007-GPS時間(原子時計の時間)(Rational)
                // 0x0008-測位に使った衛星信号(Ascii)
                // 0x0009-GPS受信機の状態(Ascii)
                // 0x000A-GPSの測位方法(Ascii)
                // 0x000B-測位の信頼性(Rational)
                // 0x000C-速度の単位(Ascii)
                // 0x000D-速度(数値)(Rational)


                if (p.Type == 2 && p.Len > 0)
                {
                    string s = System.Text.Encoding.ASCII.GetString(p.Value);
                    s = s.Trim(new char[] { '\0' });
                    System.Diagnostics.Debug.Print("{0} - [{1}][{2}]", p.Id, s, p.Type);
                }
                else
                {
                    System.Diagnostics.Debug.Print("{0} - [{1}][{2}]", p.Id, p.Value, p.Type);
                }
            }
            System.Drawing.Imaging.PropertyItem p1 = bmp.PropertyItems[0];
            {
                // 緯度
                p1.Id = 1;
                p1.Type = 2;
                p1.Value = ConvertTo("N");
                p1.Len = p1.Value.Length;
                bmp.SetPropertyItem(p1);

                p1.Id = 2;
                p1.Type = 5;
                p1.Value = ConvertTo(new UInt32[] { 38, 1, 2, 1, 37, 10 });
                p1.Len = p1.Value.Length;
                bmp.SetPropertyItem(p1);

                // 経度
                p1.Id = 3;
                p1.Type = 2;
                p1.Value = ConvertTo("E");
                p1.Len = p1.Value.Length;
                bmp.SetPropertyItem(p1);

                p1.Id = 4;
                p1.Type = 5;
                p1.Value = ConvertTo(new UInt32[] { 140, 1, 44, 1, 175, 10 });
                p1.Len = p1.Value.Length;
                bmp.SetPropertyItem(p1);

                // 高度
                p1.Id = 5;
                p1.Type = 7;
                p1.Value = new byte[] { 0x00};
                p1.Len = p1.Value.Length;
                bmp.SetPropertyItem(p1);

                p1.Id = 6;
                p1.Type = 5;
                p1.Value = ConvertTo(new UInt32[] { 40, 1 });
                p1.Len = p1.Value.Length;

                bmp.SetPropertyItem(p1);
            }


            String newPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(fileName), "HOGE.jpg");

            bmp.Save(newPath);
        }
示例#15
0
 static void compressImage(string path)
 {
     try
     {
         Bitmap origin = new Bitmap(path);
         int originWidth = origin.Width;
         int originHeight = origin.Height;
         int targetWidth = 720;
         int targetHeight = 540;
         bool flag = false;
         if (originWidth * targetHeight > originHeight * targetWidth)
         {
             if (originWidth > targetWidth)
             {
                 targetHeight = originHeight * targetWidth / originWidth;
                 flag = true;
             }
         }
         else
         {
             if (originHeight > targetHeight)
             {
                 targetWidth = originWidth * targetHeight / originHeight;
                 flag = true;
             }
         }
         if (flag)
         {
             FileInfo fileInfo = new FileInfo(path);
             Console.WriteLine("Start compress: " + fileInfo.Name);
             Console.WriteLine("(" + originWidth + ", " + originHeight + ") => (" + targetWidth + ", " + targetHeight + ")");
             Console.WriteLine("Origin size:     " + (fileInfo.Length / 1024) + " KB");
             Bitmap target = new Bitmap(targetWidth, targetHeight);
             foreach (PropertyItem propitem in origin.PropertyItems)
             {
                 target.SetPropertyItem(propitem);
             }
             for (int x = 0; x < targetWidth; ++x)
             {
                 for (int y = 0; y < targetHeight; ++y)
                 {
                     int tx = x * originWidth / targetWidth;
                     int ty = y * originHeight / targetHeight;
                     target.SetPixel(x, y, origin.GetPixel(tx, ty));
                 }
             }
             origin.Dispose();
             string extension = fileInfo.Extension.ToLower();
             if (".jpg" == extension || ".jpeg" == extension)
             {
                 EncoderParameters ps = new EncoderParameters(1);
                 ps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
                 target.Save(path, GetEncoderInfo("image/jpeg"), ps);
             }
             else
             {
                 target.Save(path);
             }
             target.Dispose();
             fileInfo = new FileInfo(path);
             Console.WriteLine("Compressed size: " + (fileInfo.Length / 1024) + " KB");
             Console.WriteLine();
         }
     }
     catch
     {
         Console.WriteLine("Error: " + path);
     }
 }
示例#16
0
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = e.Argument;

            if (backgroundWorker.CancellationPending == true) { e.Cancel = true; return; }
            backgroundWorker.ReportProgress(0, "Process Initiating");
            String sourcefile = (String)e.Argument;
            String dir = Path.GetDirectoryName(sourcefile);
            String filename = Path.GetFileNameWithoutExtension(sourcefile);

            if (backgroundWorker.CancellationPending == true) { e.Cancel = true; return; }
            backgroundWorker.ReportProgress(10, "Loading Photo");
            Image imgPhoto = Image.FromFile(sourcefile, true);
            System.Drawing.Imaging.PropertyItem[] metadata = imgPhoto.PropertyItems;
            int ImageWidth, ImageHeight, FrameThickness;
            Helper.ResizeImage(new Size(imgPhoto.Width, imgPhoto.Height), (double)Properties.Settings.Default.FrameThickness * 0.01, ImageLengthLimit,
                out ImageWidth, out ImageHeight, out FrameThickness);
            int FrameThicknessTwo = 2 * FrameThickness;

            if (backgroundWorker.CancellationPending == true) { e.Cancel = true; return; }
            backgroundWorker.ReportProgress(30, "Processing Photo");
            Bitmap bOutput = new Bitmap(ImageWidth + FrameThicknessTwo, ImageHeight + FrameThicknessTwo, imgPhoto.PixelFormat);
            bOutput.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            foreach (var data in imgPhoto.PropertyItems)
            {
                bOutput.SetPropertyItem(data);
            }
            bOutput.Tag = imgPhoto.Tag;

            if (backgroundWorker.CancellationPending == true) { e.Cancel = true; return; }
            backgroundWorker.ReportProgress(50, "Processing Photo");
            Graphics gCanvas = Graphics.FromImage(bOutput);
            gCanvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            gCanvas.SmoothingMode = SmoothingMode.AntiAlias;
            gCanvas.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

            if (backgroundWorker.CancellationPending == true) { e.Cancel = true; return; }
            backgroundWorker.ReportProgress(60, "Processing Photo");
            gCanvas.FillRectangle(new SolidBrush(Properties.Settings.Default.FrameColor), -1, -1, bOutput.Width +1, bOutput.Height + 1);
            gCanvas.DrawImage(imgPhoto, FrameThickness, FrameThickness, bOutput.Width - FrameThicknessTwo, bOutput.Height - FrameThicknessTwo);

            #region Draw Caption
            #region Scale FontSize
            float rawfontsize = (float)(FrameThickness * Properties.Settings.Default.CaptionSize);
            Font gFont = new Font(Properties.Settings.Default.CaptionFont.FontFamily,
                                    rawfontsize,
                                    Properties.Settings.Default.CaptionFont.Style,
                                    Properties.Settings.Default.CaptionFont.Unit,
                                    Properties.Settings.Default.CaptionFont.GdiCharSet,
                                    Properties.Settings.Default.CaptionFont.GdiVerticalFont);
            SizeF extent = gCanvas.MeasureString(Properties.Settings.Default.LeftSideCaption, gFont);
            float scaledfontsize = rawfontsize * (rawfontsize / extent.Height);
            gFont = new Font(Properties.Settings.Default.CaptionFont.FontFamily,
                                    scaledfontsize,
                                    Properties.Settings.Default.CaptionFont.Style,
                                    Properties.Settings.Default.CaptionFont.Unit,
                                    Properties.Settings.Default.CaptionFont.GdiCharSet,
                                    Properties.Settings.Default.CaptionFont.GdiVerticalFont);
            #endregion
            StringFormat gStringFormat = new StringFormat();
            gStringFormat.Alignment = StringAlignment.Far;
            gCanvas.DrawString(Properties.Settings.Default.LeftSideCaption,
                                gFont,
                                new SolidBrush(Properties.Settings.Default.CaptionFontColor),
                                new Point(FrameThickness, bOutput.Height - FrameThickness));
            gCanvas.DrawString(Properties.Settings.Default.RightSideCaption,
                                gFont,
                                new SolidBrush(Properties.Settings.Default.CaptionFontColor),
                                new Point(bOutput.Width - FrameThickness, bOutput.Height - FrameThickness),
                                gStringFormat);
            #endregion

            if (backgroundWorker.CancellationPending == true) { e.Cancel = true; return; }
            backgroundWorker.ReportProgress(80, "Saving Processed Photo");
            String outputfile = Path.Combine(dir, filename + "-result.jpg");
            for (int i = 2; File.Exists(outputfile); i++)
            {
                outputfile = Path.Combine(dir, filename + "-result" + i.ToString() + ".jpg");
            }
            Helper.SaveJpeg(outputfile, bOutput, 100);
        }
示例#17
0
 public void Wykonaj(Zdjecie z, Stack<object> Argumenty)
 {
     if (z.Zaznaczenie.Width != 0 && z.Zaznaczenie.Height != 0)
     {
         if (z.Zaznaczenie.Width < 0)
         {
             z.Zaznaczenie.X += z.Zaznaczenie.Width;
             z.Zaznaczenie.Width *= -1;
         }
         if (z.Zaznaczenie.Height < 0)
         {
             z.Zaznaczenie.Y += z.Zaznaczenie.Height;
             z.Zaznaczenie.Height *= -1;
         }
         Bitmap cropped = new Bitmap(Math.Abs(z.Zaznaczenie.Width), Math.Abs(z.Zaznaczenie.Height), z.Duze.PixelFormat);
         Graphics g = Graphics.FromImage(cropped);
         g.DrawImage(z.Duze, new Rectangle(0, 0, cropped.Width, cropped.Height), z.Zaznaczenie, GraphicsUnit.Pixel);
         g.Dispose();
         foreach (PropertyItem pi in z.Duze.PropertyItems)
         {
             cropped.SetPropertyItem(pi);
         }
         z.Duze = cropped;
     }
 }
示例#18
0
        /// <summary>
        /// Modifies an Profile image.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <param name="w">The w.</param>
        /// <param name="h">The h.</param>
        /// <param name="PersonID">Profile Image to work on</param>
        /// <returns>New Image Id</returns>
        private bool ModifyImage(int x, int y, int w, int h, Person person)
        {
            string ProfilDirSetting = ConfigurationManager.AppSettings["ProfileImage"];

            if (string.IsNullOrWhiteSpace(ProfilDirSetting)) { throw new ArgumentNullException(); }

            var ProfilBilled = string.Format(ProfilDirSetting, person.PersonID);

            if (System.IO.File.Exists(Server.MapPath(ProfilBilled)))
            {
                Image img = Image.FromFile(Server.MapPath(ProfilBilled));



                using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(428, 550))
                {
                    _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                    using (Graphics _graphic = Graphics.FromImage(_bitmap))
                    {
                        _graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        _graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        _graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        _graphic.Clear(Color.White);
                        //_graphic.DrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, 428, 550), x, y, w, h, GraphicsUnit.Pixel);
                        //_graphic.DrawImage(img, new Rectangle(0, 0, w, h), x, y, w, h, GraphicsUnit.Pixel);
                        //_graphic.DrawImage(img, 0, 0, img.Width, img.Height);
                        //_graphic.DrawImage(img, new Rectangle(0, 0, 428, 550), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);

                    }
                    System.Drawing.Imaging.PropertyItem prop = img.PropertyItems[0];
                    SetProperty(ref prop, 270, string.Format("Username: {0}, {1}", person.UserName, person.FullName));
                    _bitmap.SetPropertyItem(prop);
                    SetProperty(ref prop, 33432, "Copyright Natteravnene www.natteravnene.dk");
                    _bitmap.SetPropertyItem(prop);
                    //TODO: Set more properties
                    img.Dispose();

                    _bitmap.Save(Server.MapPath(ProfilBilled), System.Drawing.Imaging.ImageFormat.Jpeg);
                }

            }

            return true;
        }
示例#19
0
        public static void SaveData(string infilename, string outfilename)
        {
            //try
            //{
                string TempFile;

                TempFile = System.IO.Path.GetTempPath() + "__ImageCaptionEdit__" + System.IO.Path.GetRandomFileName();
                System.IO.File.Copy(infilename, TempFile);

                Encoding _Encoding = Encoding.UTF8;
                Image theImage = new Bitmap(TempFile);

                //figure out how to create an EXIF propertyitem...
                //PropertyItem BaseProperty = new PropertyItem();
                PropertyItem BaseProperty;

                BaseProperty = CreatePropertyItem();

                theImage.SetPropertyItem(SetupProperty(BaseProperty, header, 0x9c9b));
                theImage.SetPropertyItem(SetupProperty(BaseProperty, sideinfo, 0x9c9f));
                theImage.SetPropertyItem(SetupProperty(BaseProperty, description, 0x9c9c));

                theImage.Save(outfilename,ImageFormat.Jpeg);

            //}
            //catch (Exception excp)
            //{
            //    MessageBox.Show("Error in SaveData: " + excp.Message);
            //}
        }
示例#20
0
        public DlgPhotoDraw(Waypoint wpt, PhotoDescr photoDescr)
        {
            if(photoDescr != null)
            {
                // from DlgPhotoFullSize, wpt may be null
                m_photoDescr = PhotoDescr.FromPhotoDescr(photoDescr);		// with null image
                m_photoDescr.imageDisposable = false;
                m_photoDescr.ensureOriginalImageExists();		// local will be still invoked if not a gallery
            }
            else
            {
                // from right-click on a waypoint; wpt must be non-null
                try
                {
                    m_photoDescr = PhotoDescr.FromThumbnail(wpt.ThumbSource);
                    m_photoDescr.imageDisposable = false;
                    m_photoDescr.ensureOriginalImageExists();		// local will be still invoked if not a gallery
                }
                    // An invalid image will throw an OutOfMemoryException
                    // exception
                catch (OutOfMemoryException)
                {
                    throw new Exception("Corrupted image file?");
                }
            }
            originalOrientation = m_photoDescr.Orientation;
            m_photoDescr.Orientation = 1;			// will force display to actual orientation, no adjustment
            originalBitmap = new Bitmap(m_photoDescr.image);
            whRatio = (double)originalBitmap.Width / (double)originalBitmap.Height;

            foreach(PropertyItem item in m_photoDescr.image.PropertyItems)
            {
                //string str = "" + item.Type + ": " + item.Id + "=" + item.Value;
                //LibSys.StatusBar.Trace(str);
                originalBitmap.SetPropertyItem(item);
            }

            m_wpt = wpt;

            InitializeComponent();

            addExifCoordsCheckBox.Enabled = (m_wpt != null);
            addExifCoordsCheckBox.Checked = m_addExifCoords;

            this.linkToWptLinkLabel.Enabled = (m_wpt == null || m_wpt.TrackId == -1);

            this.photoViewerControl = new LibSys.PhotoViewerControl();
            this.picturePanel.Controls.AddRange(new System.Windows.Forms.Control[] { this.photoViewerControl});
            //
            // photoViewerControl
            //
            this.photoViewerControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.photoViewerControl.Name = "photoViewerControl";
            //this.photoViewerControl.photoDescr = null;
            this.photoViewerControl.TabIndex = 1;

            photoViewerControl.fitToSize = m_fitToSize;
            fitToSizeCheckBox.Checked = m_fitToSize;
            this.fitToSizeCheckBox.CheckedChanged += new System.EventHandler(this.fitToSizeCheckBox_CheckedChanged);

            if(m_wpt != null && m_wpt.TrackId != -1)
            {
                timeTptRadioButton.Checked = true;
                this.timePanel.Enabled = true;
            }
            else
            {
                timeExifRadioButton.Checked = true;
                timePanel.Enabled = false;
            }

            setTextTextBox();

            widthTextBox.Text = "" + originalBitmap.Width;		// Y will be set in validation
            widthTextBox_Validating(null, null);

            draw(false);

            if(Project.fitsScreen(m_dlgSizeX, m_dlgSizeY, m_dlgSizeWidth, m_dlgSizeHeight))
            {
                inResize = true;
                this.Location = new Point(m_dlgSizeX, m_dlgSizeY);
                this.ClientSize = new System.Drawing.Size(m_dlgSizeWidth, m_dlgSizeHeight);		// causes Resize()
            }

            // PhotoProperties related:
            // Create an instance of a ListView column sorter and
            // assign it to the _listView control.
            lvwColumnSorter = new ListViewColumnSorter();
            this._listView.ListViewItemSorter = lvwColumnSorter;

            _resultOptions = new ResultOptions();

            // end of PhotoProperties related.

            positionComboBox.SelectedIndex = m_position;
            this.positionComboBox.SelectedIndexChanged += new System.EventHandler(this.positionComboBox_SelectedIndexChanged);

            m_fontSize = (int)Math.Round(Math.Max(originalBitmap.Width / 50.0d, m_fontSize));
            fontNumericUpDown.Value = Math.Min(m_fontSize, fontNumericUpDown.Maximum);

            qualityNumericUpDown.Value = Project.photoSaveQuality;
            this.qualityNumericUpDown.ValueChanged += new System.EventHandler(this.qualityNumericUpDown_ValueChanged);

            applyTextCheckBox.Checked = true;
            pickColorButton.BackColor = m_color;
            pickBgColorButton.BackColor = m_bgColor;
            this.useBgColorCheckBox.Checked = m_useBgColor;

            this.Text += " - " + m_photoDescr.imageName;

            switch(originalOrientation)
            {
                    // see PhotoDescr.cs for EXIF orientation codes:
            //				case 4:
            //					//thumb.RotateFlip(RotateFlipType.Rotate180FlipNone);
            //					break;
                case 8:
                    this.rotate270RadioButton.Checked = true;
                    //thumb.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    break;
                case 6:
                    this.rotate90RadioButton.Checked = true;
                    //thumb.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    break;
                default:
                    this.rotate0RadioButton.Checked = true;
                    break;
            }

            this.saveButton.Enabled = false;
            this.previewLinkLabel.Enabled = false;

            Project.setDlgIcon(this);
        }
示例#21
0
        void ShrinkImages(int Width, string inputFolder, string outputFolder)
        {
            float newWidth = (float)Width;

            try
            {

                if (false == Directory.Exists(inputFolder))
                    return;

                //Get all the *.jpg files (pictures) in "." this directory
                DirectoryInfo di = new DirectoryInfo(inputFolder);
                FileInfo[] pictures = di.GetFiles("*.jpg");
                if (pictures.Length < 1)
                {
                    throw new Exception("No JPEG(picture) files found in input folder.");
                }

                try
                {
                    if (false == Directory.Exists(outputFolder))
                        Directory.CreateDirectory(outputFolder);
                }
                catch(Exception exp)
                {
                    throw new Exception("Output folder error\r\n:" + exp.Message);
                }

                progressBar1.Maximum = pictures.Length;
                progressBar1.Minimum = 0;
                progressBar1.Value = 0;

                Image oldImage = null;
                Image shrunkImage = null;
                Graphics oGraphic = null;

                string directoryPath, newName;
                int smallHeight, smallWidth;

                float shrinkFactor;

                foreach (FileInfo fileinfo in pictures)
                {
                    progressBar1.Value++;

                    try
                    {
                        oldImage = Image.FromFile(fileinfo.FullName);

                        if (oldImage.Width <= newWidth)
                        {
                            Console.WriteLine("Skipping " + fileinfo.Name + "...");
                            continue;// skip this image nothing to do already small
                        }

                        Console.WriteLine("Shrinking " + fileinfo.Name + "...");
                        UpdateStatus("Shrinking " + fileinfo.Name + "...");

                        if (oldImage.Height < oldImage.Width) //Landscape
                            shrinkFactor = oldImage.Width / newWidth;
                        else //Portrait;
                            shrinkFactor = oldImage.Height / newWidth;

                        smallHeight = (int)(oldImage.Height / shrinkFactor);
                        smallWidth = (int)(oldImage.Width / shrinkFactor);

                        //Create new (blank) Image object called "shrunkImage" of new smaller size (canvas)
                        shrunkImage = new Bitmap(smallWidth, smallHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                        //Create new Graphics object called "oGraphic" based on object "shrunkImage"
                        //with multiple quality attributes
                        oGraphic = Graphics.FromImage(shrunkImage);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        byte oldImageOrinentation = 1;

                        //Set attribute of object "oGraphic" to rectangle of new smaller size (photo on canvas)
                        Rectangle rect = new Rectangle(0, 0, smallWidth, smallHeight);

                        //Draw the old photo in the new rectangle
                        oGraphic.DrawImage(oldImage, rect);

                        //Copy over jpeg meta data (PropertyItems)
                        foreach (PropertyItem item in oldImage.PropertyItems)
                        {
                            if ((Orientation == item.Id) || (Thumbnail_Orientation == item.Id))
                            {
                              if (item.Type == 0x3)//3 = SHORT A 16-bit (2 -byte) unsigned integer,
                                {

                                   byte test = item.Value[0];

                                   //Lets not write corrected orientation. We will remove orientation all together
                                   //if ((test == 8) || (test == 3) || (test == 5))
                                   // {
                                   //     item.Value[0] = 0x01;
                                   //     item.Value[1] = 0x00;
                                   // }

                                    if (Orientation == item.Id)
                                        oldImageOrinentation = test; //note orientation will use later

                                }
                            }

                            if (true == checkBoxFixOrientation.Checked)
                            {
                                //Do not copy to new image propety item if pertains to oritentation
                                //As we will rotate image as need later
                                if ((Orientation != item.Id) && (Thumbnail_Orientation != item.Id))
                                    shrunkImage.SetPropertyItem(item);
                            }
                            else
                            {
                                shrunkImage.SetPropertyItem(item);
                            }
                        }// foreach PropertyItem item

                        //Save as a JPEG
                        //directoryPath = System.IO.Path.GetDirectoryName(fileinfo.FullName);
                        directoryPath = outputFolder;
                        newName = directoryPath + "\\" + "s" + ((int)newWidth) + "-" + fileinfo.Name;

                        if (true == checkBoxFixOrientation.Checked)
                        {
                            switch (oldImageOrinentation)
                            {
                                case 8://->
                                    shrunkImage.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                                    break;
                                case 3:
                                    shrunkImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                                    break;
                                case 6:
                                    shrunkImage.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                                    break;
                                default:
                                    break;
                            }

                        }

                        shrunkImage.Save(newName, ImageFormat.Jpeg);

                    }
                    catch (Exception exp)
                    {
                       MessageBox.Show(exp.Message, "Shrink Images",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        if (oldImage != null) oldImage.Dispose();
                        if (shrunkImage != null) shrunkImage.Dispose();
                        if (oGraphic != null) oGraphic.Dispose();
                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Shrink Images",
                     MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                OperationComplete();
            }
        }
示例#22
0
 static void ProcessImage(string image, string outpath)
 {
     var timage = image;
     try {
         DateTime datePicture = DateTime.MinValue;
         try {
             using (ExifReader reader = new ExifReader(timage)) {
                 DateTime datePictureTaken;
                 if (reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized, out datePictureTaken)) {
                     datePicture = datePictureTaken;
                 }
             }
         }
         catch (Exception) {
         }
         if (datePicture.Equals(DateTime.MinValue)) {
             var date = File.GetLastWriteTime(timage);
             Console.WriteLine("Can't determine date. " + timage + " Use file date: ( " + date.ToShortDateString() + " - " + date.ToShortTimeString() + " ) ? (y/n)");
             if (Console.ReadKey().KeyChar.ToString().ToUpper().Equals("Y")) {
                 datePicture = date;
                 Encoding _Encoding = Encoding.UTF8;
                 Image theImage = new Bitmap(image);
                 // 36867 = DateTimeOriginal
                 // 36868 = DateTimeDigitized
                 PropertyItem prop = theImage.PropertyItems[0];
                 SetProperty(ref prop, 36868, date.ToString("yyyy:MM:dd HH:mm:ss"));
                 theImage.SetPropertyItem(prop);
                 theImage.Save(timage + ".tmp");
                 timage = timage + ".tmp";
             }
         }
         if (!datePicture.Equals(DateTime.MinValue)) {
             int i = 1;
             while (File.Exists(DateToFile(outpath, datePicture, i))) {
                 i++;
             }
             //Console.WriteLine(DateToFile(outpath, datePicture, i));
             if (!Directory.Exists(DateToYear(outpath, datePicture))) {
                 Directory.CreateDirectory(DateToYear(outpath, datePicture));
             }
             if (!Directory.Exists(DateToYearMonth(outpath, datePicture))) {
                 Directory.CreateDirectory(DateToYearMonth(outpath, datePicture));
             }
             File.Move(timage, DateToFile(outpath, datePicture, i));
         }
     }
     catch (Exception e) {
         Console.WriteLine(timage + ": " + e.Message);
     }
 }
示例#23
0
        public void MakeThumbnail( string thumbnailPath, int width, int height,ref string msg)
        {
            int buffer_count = 2048;
            byte[] buffer = new byte[buffer_count];
            //缩略图画布宽高  
            int towidth = width;
            int toheight = height;
            //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)  
            int x = 0;
            int y = 0;
            int ow = ResourceImage.Width;
            int oh = ResourceImage.Height;
            if (ow == width && oh == height)
            {
                msg = "exists";
                return;
            }
            //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)  
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            //倍数变量  
            double multiple = 0;
            //获取宽长的或是高长与缩略图的倍数  
            if (ResourceImage.Width >= ResourceImage.Height)
                multiple = (double)ResourceImage.Width / (double)width;
            else
                multiple = (double)ResourceImage.Height / (double)height;
            //上传的图片的宽和高小等于缩略图  
            if (ow <= width && oh <= height)
            {
                //缩略图按原始宽高  
                bg_w = ResourceImage.Width;
                bg_h = ResourceImage.Height;
                //空白部分用背景色填充  
                bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
                bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
            }
                //上传的图片的宽和高大于缩略图  
            else
            {
                //宽高按比例缩放  
                bg_w = Convert.ToInt32((double)ResourceImage.Width / multiple);
                bg_h = Convert.ToInt32((double)ResourceImage.Height / multiple);
                //空白部分用背景色填充  
                bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
                bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
            }
            //新建一个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.AntiAlias;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分  
            //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素  
            g.DrawImage(ResourceImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            //g.DrawImage(ResourceImage, x, y, bg_w, bg_h);
            try
            {
                ImageCodecInfo ici = ImageCodecInfo.GetImageEncoders().FirstOrDefault(p => p.FormatID == ResourceImage.RawFormat.Guid);
                //EncoderParameters paras = ResourceImage.GetEncoderParameterList(ici.Clsid);
                System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
                ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);

                //获取图片类型
                string fileExtension = System.IO.Path.GetExtension(_imageFileName).ToLower();
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.  
                foreach (PropertyItem i in ResourceImage.PropertyItems)
                {
                    bitmap.SetPropertyItem(i);
                }
                //switch (fileExtension)
                //{
                //    case ".gif": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;
                //    case ".jpg": bitmap.Save(thumbnailPath,ici,ep); break;//, System.Drawing.Imaging.ImageFormat.Jpeg
                //    case ".bmp": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break;
                //    case ".png": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
                //}
                bitmap.Save(thumbnailPath, ici, ep);
            } catch (System.Exception e)
            {
                throw e;
            } finally
            {
                ResourceImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
示例#24
0
文件: Form1.cs 项目: Hagser/csharp
        private void ResizeImage(object state)
        {
            FileInfo fi = new FileInfo(state as string);

            System.GC.Collect();
            Image img = Bitmap.FromFile(fi.FullName);
            if (img.Width > 2690)
            {
                PropertyItem[] itms = img.PropertyItems;
                System.GC.Collect();
                img = new Bitmap(Bitmap.FromFile(fi.FullName),
                int.Parse(Math.Floor(img.Width * .5).ToString()),
                int.Parse(Math.Floor(img.Height * .5).ToString()));

                foreach (PropertyItem pi in itms)
                {
                    img.SetPropertyItem(pi);
                }

                System.GC.Collect();
                string newfilename = fi.DirectoryName + "\\" + fi.Name.Replace(".JPG", "~.JPG").Replace(".jpg", "~.jpg");
                img.Save(newfilename, ImageFormat.Jpeg);
                System.GC.Collect();
                img = null;
                System.GC.Collect();
                try
                {

                    var arg = new { nf = newfilename, fi = fi };
                    fi = null;
                    Action act = new Action(delegate
                    {
                        System.IO.File.SetCreationTime(arg.nf, arg.fi.CreationTime);
                        System.IO.File.SetLastAccessTime(arg.nf, arg.fi.LastAccessTime);
                        System.IO.File.SetLastWriteTime(arg.nf, arg.fi.LastWriteTime);
                        System.IO.File.Delete(arg.fi.FullName);
                        System.IO.File.Move(arg.nf, arg.fi.FullName);
                    });
                    MoveFile(act, 0);
                }
                catch
                {

                }
            }
            else
            {
                img = null;
            }
            System.GC.Collect();
            icnt++;
            this.Invoke((MethodInvoker)delegate { this.Text = "MyPhotoEditor " + icnt + "/" + icntlist; });
            if (icntlist <= icnt)
            {
                MessageBox.Show("Jupp");
            }            
        }
示例#25
0
        private void setGpsExifTags(Bitmap bitmap)
        {
            if(m_bitmap.PropertyItems.GetLength(0) == 0)
            {
                return;
            }

            //Bitmap bTmp = originalBitmap;
            Bitmap bTmp = m_bitmap;

            // see PhotoDescr.cs for formatting info:
            PropertyItem item = bTmp.PropertyItems[0];
            //PropertyItem item = bitmap.PropertyItems[0];
            item.Id = 1;
            item.Type = 2;
            item.Value = enc.GetBytes(m_wpt.Location.Lat >= 0.0d ? "N" : "S");
            item.Len = item.Value.GetLength(0);
            bitmap.SetPropertyItem(item);

            item = bTmp.PropertyItems[0];
            item.Id = 2;
            item.Type = 5;
            item.Value = PhotoDescr.ToPackedRationalCoord(m_wpt.Location.Lat);
            item.Len = item.Value.GetLength(0);
            bitmap.SetPropertyItem(item);

            item = bTmp.PropertyItems[0];
            item.Id = 3;
            item.Type = 2;
            item.Value = enc.GetBytes(m_wpt.Location.Lng >= 0.0d ? "E" : "W");
            item.Len = item.Value.GetLength(0);
            bitmap.SetPropertyItem(item);

            item = bTmp.PropertyItems[0];
            item.Id = 4;
            item.Type = 5;
            item.Value = PhotoDescr.ToPackedRationalCoord(m_wpt.Location.Lng);
            item.Len = item.Value.GetLength(0);
            bitmap.SetPropertyItem(item);
        }
示例#26
0
        /// <summary>
        /// Crops the image in the middle resizing it down to fit as much of the image as possible. Note, image is not enlarged to fit desired width and height.
        /// </summary>
        /// <param name="width">The desired width to crop the image to, set to null to not perform horizontal cropping.</param>
        /// <param name="height">The desired height to crop the image to, set to null to not perform vertical cropping.</param>
        /// <returns>A reference to this object to allow chaining operations together.</returns>
        public ImageMedia Crop(int? width, int? height)
        {
            if (width == null && height == null)
                return this;

            int w = (width == null) ? _source.Width : width.Value;
            int h = (height == null) ? _source.Height : height.Value;

            float scaleX = (float)w / (float)_source.Width;
            float scaleY = (float)h / (float)_source.Height;
            float scale = Math.Max(scaleX, scaleY);
            int marginX = -((int)(_source.Width * scale - w)) / 2;
            int marginY = -((int)(_source.Height * scale - h)) / 2;

            Image resizedImage = new Bitmap(w, h);
            Graphics g = Graphics.FromImage(resizedImage);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.FillRectangle(new SolidBrush(Color.Transparent), 0, 0, w, h);
            g.DrawImage(_source, marginX, marginY, _source.Width * scale, _source.Height * scale);

            foreach (PropertyItem item in _source.PropertyItems)
                resizedImage.SetPropertyItem(item);

            _source = resizedImage;
            _data = null;
            return this;
        }
示例#27
0
文件: Resizer.cs 项目: pirahawk/6wzyc
        static async Task CopyImage(ImageData imageData, ImageCodecInfo jpgEncoder, EncoderParameters parameters)
        {
            //await Task.Yield();


            using (var originalImage = Bitmap.FromFile(imageData.SourcePath))
            {
                //originalImage.PropertyItems.Where(pi => pi.)



                var width = originalImage.Width;
                var height = originalImage.Height;
                var isLandscape = width > height;

                //if (width == 1880 && height == 2816) //ignore shots from vending machine for a second
                //{
                //    Console.WriteLine($"skipping copy for image {imageData.SourcePath}");
                //    return;
                //}

                //var destinationWidth = isLandscape ? 640 : 427; //preview
                //var destinationHeight = isLandscape ? 427 : 640; //preview

                var destinationWidth = isLandscape ? 320 : 214; //preview
                var destinationHeight = isLandscape ? 214 : 320; //preview

                using (var ms = new MemoryStream())
                {
                    using (var newImage = new Bitmap(destinationWidth, destinationHeight))
                    {
                        using (var graphics = Graphics.FromImage(newImage))
                        {
                            //Resize the image
                            graphics.SmoothingMode = SmoothingMode.AntiAlias;
                            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            graphics.DrawImage(originalImage, new Rectangle(0, 0, destinationWidth, destinationHeight));


                            //const long quality = 80L;
                            //var qualityParam = System.Drawing.Imaging.Encoder.Quality;
                            //var jpgEncoder = ImageCodecInfo.GetImageDecoders().First(enc => enc.FormatID == ImageFormat.Jpeg.Guid);
                            //var parameters = new EncoderParameters(1);
                            //parameters.Param[0] = new EncoderParameter(qualityParam, quality);

                            //newImage.Save(imageData.DestinationPath, jpgEncoder, parameters);

                            //Copy exif properties otherwise the images may rotate wierdly
                            foreach (var item in originalImage.PropertyItems)
                            {
                                newImage.SetPropertyItem(item);
                            }
                            newImage.Save(ms, jpgEncoder, parameters);

                            //Write the File out
                            ms.Position = 0;
                            using (var fs = new FileStream(imageData.DestinationPath, FileMode.Create))
                            {
                                await ms.CopyToAsync(fs);
                            }
                        }
                    }
                }
            }
        }
示例#28
0
 /// <summary>
 /// Metoda statyczna tworzaca nowa bitmape z podanego obrazu
 /// </summary>
 /// <param name="i">Obraz</param>
 /// <returns>Bitmapa</returns>
 public static Bitmap FromImage(Image i)
 {
     Bitmap from = null;
     try
     {
         from = new Bitmap(i);
     }
     catch (System.Runtime.InteropServices.ExternalException)
     {
         from = new Bitmap(Properties.Resources.blad);
     }
     foreach (PropertyItem pi in i.PropertyItems)
     {
         from.SetPropertyItem(pi);
     }
     return from;
 }
示例#29
0
        /// <summary>
        /// Opens a document from a jpeg file with embedded QuickRoute Jpeg Extension Data.
        /// </summary>
        /// <param name="fileName">The file name of the jpeg file.</param>
        /// <param name="settings">The document settings to apply.</param>
        /// <returns>A QuickRoute document if the jpeg file contains QuickRoute Jpeg Extension Data, otherwise null.</returns>
        public static Document OpenFromJpeg(string fileName, DocumentSettings settings)
        {
            var ed = QuickRouteJpegExtensionData.FromJpegFile(fileName);
              if (ed == null) return null;
              var mapAndBorderImage = (Bitmap)Image.FromFile(fileName);

              var mapImage = new Bitmap(ed.MapLocationAndSizeInPixels.Width, ed.MapLocationAndSizeInPixels.Height);
              using(var g = Graphics.FromImage(mapImage))
              {
            g.DrawImage(mapAndBorderImage,
                    new Rectangle(0, 0, ed.MapLocationAndSizeInPixels.Width, ed.MapLocationAndSizeInPixels.Height),
                    ed.MapLocationAndSizeInPixels,
                    GraphicsUnit.Pixel);
              }
              foreach(var pi in mapAndBorderImage.PropertyItems)
              {
            mapImage.SetPropertyItem(pi);
              }

              var exif = new ExifWorks.ExifWorks(ref mapAndBorderImage);
              var qualityByteArray = exif.GetProperty((int)ExifWorks.ExifWorks.TagNames.JPEGQuality, new byte[] { 80 });

              var encodingInfo = new JpegEncodingInfo((double)qualityByteArray[0] / 100);
              using (var ms = new MemoryStream())
              {
            mapImage.Save(ms, encodingInfo.Encoder, encodingInfo.EncoderParams);
            var document = new Document(new Map(ms), settings) { Sessions = ed.Sessions };
            if (document.Sessions.Count > 0) document.ProjectionOrigin = document.Sessions[0].ProjectionOrigin;
            document.FileName = fileName;
            document.FileFormat = QuickRouteFileFormat.Jpeg;
            document.Initialize();
            mapAndBorderImage.Dispose();
            mapImage.Dispose();
            return document;
              }
        }
        /// <summary>
        /// The worker function for patch processing. This is to be started as a separate thread.
        /// </summary>
        private void processPhotos()
        {
            Random r = new Random((int)DateTime.Now.Ticks);
            List<string> files = new List<string>();

            files.AddRange(Directory.GetFiles(path, "*.jpg"));
            files.AddRange(Directory.GetFiles(path, "*.jpeg"));

            this.BeginInvoke((Action)(() => progressBar1.Value = 0));
            this.BeginInvoke((Action)(() => progressBar1.Step = 1));
            this.BeginInvoke((Action)(() => progressBar1.Maximum = files.Count + 1));
            this.BeginInvoke((Action)(() => progressBar1.PerformStep())); // do one progress bar step immediately to indicate we have started processing

            foreach (string file in files)
            {
                exifDateString = combinedTime.ToString("yyyy:MM:dd HH:mm:ss");

                // set EXIF data to specified time
                // http://www.media.mit.edu/pia/Research/deepview/exif.html
                //0x0132 	DateTime 	ascii string 	20 	Date/Time of image was last modified. Data format is "YYYY:MM:DD HH:MM:SS"+0x00, total 20bytes. In usual, it has the same value of DateTimeOriginal(0x9003)
                //0x9003 	DateTimeOriginal 	ascii string 	20 	Date/Time of original image taken. This value should not be modified by user program.
                //0x9004 	DateTimeDigitized 	ascii string 	20 	Date/Time of image digitized. Usually, it contains the same value of DateTimeOriginal(0x9003).
                // http://archive.msdn.microsoft.com/changexifwithcsharp
                Image iOrig = new Bitmap(file);
                ImageFormat ifOrig = iOrig.RawFormat;
                PropertyItem exifDateTimeProp = iOrig.GetPropertyItem(EXIF_DATE_TIME);
                PropertyItem exifDateTimeOrigProp = iOrig.GetPropertyItem(EXIF_DATE_TIME_ORIGINAL);
                PropertyItem exifDateTimeDigiProp = iOrig.GetPropertyItem(EXIF_DATE_TIME_DIGITIZED);

                exifDateTimeProp.Value = System.Text.Encoding.UTF8.GetBytes(exifDateString);
                exifDateTimeOrigProp.Value = System.Text.Encoding.UTF8.GetBytes(exifDateString);
                exifDateTimeDigiProp.Value = System.Text.Encoding.UTF8.GetBytes(exifDateString);

                iOrig.SetPropertyItem(exifDateTimeProp);
                iOrig.SetPropertyItem(exifDateTimeOrigProp);
                iOrig.SetPropertyItem(exifDateTimeDigiProp);

                Image iSave = new Bitmap(iOrig.Width, iOrig.Height, iOrig.PixelFormat);
                Graphics gSave = Graphics.FromImage(iSave);

                gSave.DrawImage(iOrig, 0, 0, iOrig.Width, iOrig.Height);

                foreach (PropertyItem i in iOrig.PropertyItems)
                    iSave.SetPropertyItem(i);

                // WHAT THE F**K?!
                // You *HAVE* to dispose these two objects, iOrig and gSave, BEFORE you save iSave otherwise
                // you'll get an unexplained GDI+ exception... THANK YOU MICROSOFT! >:(
                iOrig.Dispose();
                gSave.Dispose();

                iSave.Save(file, ifOrig);

                iSave.Dispose();

                // set file create, mod, and access time to the specified time
                // (this has to be done after the EXIF modification because that will modify the file, of course)

                File.SetCreationTime(file, combinedTime);
                File.SetLastWriteTime(file, combinedTime);
                File.SetLastAccessTime(file, combinedTime);

                if (chkRandomize.Checked)
                { // randomize the time to between 0800 and 1600 to make it believable:
                    int hour = r.Next(8, 17);
                    int minute = r.Next(60);
                    int second = r.Next(60);
                    int millisecond = r.Next(1000);

                    combinedTime = new DateTime(combinedTime.Year, combinedTime.Month, combinedTime.Day, hour, minute, second, millisecond);
                }

                // do progressbar step after we finished a file to give accurate feedback
                this.BeginInvoke((Action)(() => progressBar1.PerformStep()));
            }

            MessageBox.Show("Finished Processing.", "Success");
            this.BeginInvoke((Action)(() => progressBar1.Value = 0));
        }
示例#31
0
        public static Image Resize(this Image source, Size newSize, long quality, ContentAlignment contentAlignment, ThumbMode mode)
        {
            //Reference: http://www.cnblogs.com/dao/archive/2008/02/24/1079571.html
            if (newSize.IsEmpty || source.Size.IsEmpty) return source;

            //先取一個寬比例。
            double scale = (double)source.Width / (double)newSize.Width;

            //縮略模式
            switch (mode)
            {
                case ThumbMode.Full:
                    if (source.Height > source.Width)
                        scale = (double)source.Height / (double)newSize.Height;
                    break;
                case ThumbMode.Max:
                    if (source.Height / scale < newSize.Height)
                        scale = (double)source.Height / (double)newSize.Height;
                    break;
            }

            SizeF newSzie = new SizeF((float)(source.Width / scale), (float)(source.Height / scale));
            Bitmap newImage = new Bitmap(newSize.Width, newSize.Height);

            if(!source.PropertyItems.IsNullOrEmpty())
            {
                foreach (PropertyItem propertyItem in source.PropertyItems)
                {
                    newImage.SetPropertyItem(propertyItem);
                }
            }

            using (Graphics g = Graphics.FromImage(newImage))
            {
                g.FillRectangle(Brushes.White, new Rectangle(new Point(0, 0), newSize));
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.CompositingMode = CompositingMode.SourceOver;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                //對齊方式
                RectangleF destRect;
                switch (contentAlignment)
                {
                    case ContentAlignment.TopCenter:
                        destRect = new RectangleF(new PointF(-(float)((newSzie.Width - newSize.Width) * 0.5), 0), newSzie);
                        break;
                    case ContentAlignment.TopRight:
                        destRect = new RectangleF(new PointF(-(float)(newSzie.Width - newSize.Width), 0), newSzie);
                        break;
                    case ContentAlignment.MiddleLeft:
                        destRect = new RectangleF(new PointF(0, -(float)((newSzie.Height - newSize.Height) * 0.5)), newSzie);
                        break;
                    case ContentAlignment.MiddleCenter:
                        destRect = new RectangleF(new PointF(-(float)((newSzie.Width - newSize.Width) * 0.5), -(float)((newSzie.Height - newSize.Height) * 0.5)), newSzie);
                        break;
                    case ContentAlignment.MiddleRight:
                        destRect = new RectangleF(new PointF(-(float)(newSzie.Width - newSize.Width), -(float)((newSzie.Height - newSize.Height) * 0.5)), newSzie);
                        break;
                    case ContentAlignment.BottomLeft:
                        destRect = new RectangleF(new PointF(0, -(float)(newSzie.Height - newSize.Height)), newSzie);
                        break;
                    case ContentAlignment.BottomCenter:
                        destRect = new RectangleF(new PointF(-(float)((newSzie.Width - newSize.Width) * 0.5), -(float)(newSzie.Height - newSize.Height)), newSzie);
                        break;
                    case ContentAlignment.BottomRight:
                        destRect = new RectangleF(new PointF(-(float)(newSzie.Width - newSize.Width), -(float)(newSzie.Height - newSize.Height)), newSzie);
                        break;
                    default:
                        destRect = new RectangleF(new PointF(0, 0), newSzie);
                        break;
                }
                g.DrawImage(source, destRect, new RectangleF(new PointF(0F, 0F), source.Size), GraphicsUnit.Pixel);

                //source.Dispose();
            }

            return newImage;
        }
示例#32
0
        private static void ResizeBySize(Image image, Stream stream, ImageCodecInfo codec, EncoderParameters param, int w, int h)
        {
            using (Image imageNew = new Bitmap(w, h, image.PixelFormat))
            {
                using (Graphics g = Graphics.FromImage(imageNew))
                {
                    foreach (PropertyItem propertyItem in image.PropertyItems)
                        imageNew.SetPropertyItem(propertyItem);

                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    g.SmoothingMode = SmoothingMode.AntiAlias;

                    g.DrawImage(image, 0, 0, w, h);
                }

                stream.SetLength(0);
                imageNew.Save(stream, codec, param);
            }
        }