Example #1
2
 /// <summary>
 ///
 /// </summary>
 /// <param name="image"></param>
 /// <param name="id"></param>
 /// <param name="type"></param>
 /// <param name="value"></param>
 public static void Add(System.Drawing.Image image, int id, short type, byte[] value)
 {
     try
     {
         if (image.PropertyItems.Length > 0)
         {
             PropertyItem pi = image.PropertyItems[0];
             pi.Id    = id;
             pi.Type  = type;
             pi.Len   = value.Length;
             pi.Value = value;
             image.SetPropertyItem(pi);
         }
         else
         {
             //PropertyItem pi = image.GetPropertyItem(id);
             PropertyItem pi = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
             pi.Id    = id;
             pi.Type  = type;
             pi.Len   = value.Length;
             pi.Value = value;
             image.SetPropertyItem(pi);
         }
     }
     catch (ArgumentException)
     {
         return;
     }
 }
Example #2
2
 /// <summary>
 ///
 /// </summary>
 /// <param name="image"></param>
 /// <param name="id"></param>
 public static void Change(System.Drawing.Image image, int id, byte[] value)
 {
     if (image is System.Drawing.Image && ExifFormat.Contains(image.RawFormat))
     {
         var pi = image.GetPropertyItem(id);
         pi.Value = value;
         image.SetPropertyItem(pi);
     }
 }
Example #3
1
        public static bool AddMetadata(Image img, int id, string text)
        {
            PropertyItem pi;

            try
            {
                pi = (PropertyItem)typeof(PropertyItem).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { }, null).Invoke(null);
                pi.Id = id;
                pi.Len = text.Length + 1;
                pi.Type = 2;
                byte[] bytesText = Encoding.ASCII.GetBytes(text + " ");
                bytesText[bytesText.Length - 1] = 0;
                pi.Value = bytesText;

                if (pi != null)
                {
                    img.SetPropertyItem(pi);
                    return true;
                }
            }
            catch (Exception e)
            {
                DebugHelper.WriteException(e, "Reflection fail");
            }

            return false;
        }
 public static void Copy(Image source, Image target)
 {
     foreach (var propertyItem in source.PropertyItems)
     {
         target.SetPropertyItem(propertyItem);
     }
 }
Example #5
1
        private void Normalize()
        {
            bool rotated = false;

            try
            {
                var property   = image.GetPropertyItem(OrientationPropertyId);
                var rotateFlip = GetCurrentImageOrientation(GetPropertyValue(property)).GetNormalizationRotation();

                property.Value = BitConverter.GetBytes((short)1);
                image.SetPropertyItem(property);

                if (rotateFlip != RotateFlipType.RotateNoneFlipNone)
                {
                    rotated = true;
                    image.RotateFlip(rotateFlip);
                }
            }
            catch (Exception)
            {
                // Possible image does not have EXIF properties. May simple rotation
            }

            if (image.Width > image.Height)
            {
                image.RotateFlip(rotated ? RotateFlipType.Rotate270FlipNone : RotateFlipType.Rotate90FlipNone);
            }
        }
 public static void CopyEXIF(Image from, Image to)
 {
     // This should work most the time.  Could on Vista and below get
     // some improved results with WIC
     foreach (PropertyItem pi in from.PropertyItems)
     {
         to.SetPropertyItem(pi);
     }
 }
 private static void SetPropertyItemString(Image srcImg, ImageMetadataPropertyId id, string value)
 {
     var buffer = Encoding.Unicode.GetBytes(value);
     var propItem = srcImg.GetPropertyItem(srcImg.PropertyItems[0].Id);
     propItem.Id = (int)id;
     propItem.Type = 1;
     propItem.Len = buffer.Length;
     propItem.Value = buffer;
     srcImg.SetPropertyItem(propItem);
 }
Example #8
0
		public static void SaveThumbnail(Image thumb, ushort rating, string filePath)
		{
			string thumbPath = GetThumbPath(filePath);
			if (ratingProperty == null)
			{
				System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ThumbUtility));
				ratingProperty = ((System.Drawing.Image)(resources.GetObject("rating"))).GetPropertyItem(18246);
			}
			ratingProperty.Value = BitConverter.GetBytes(rating);
			thumb.SetPropertyItem(ratingProperty);
			thumb.Save(thumbPath, ImageFormat.Jpeg);
		}
Example #9
0
 private static void CopyMetadata(PropertyItem[] properties, Image target)
 {
     foreach (PropertyItem property in properties)
     {
         try {
             target.SetPropertyItem(property);
         }
         catch (ArgumentException) {
             // just ignore it; on some configurations this fails
         }
     }
 }
        private static void AddDescriptionToImage(Image image, string description)
        {
            //create a new property item
            var newItem = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
            // Change the ID of the PropertyItem. to description
            newItem.Id = 0x010E;
            newItem.Value = Encoding.UTF8.GetBytes(description);
            newItem.Len = newItem.Value.Length;
            newItem.Type = 1;//byte array

            // Set the PropertyItem for the image.
            image.SetPropertyItem(newItem);
        }
Example #11
0
        private static void WriteExifString(Image image, int id, string value)
        {
            var data = new byte[value.Length + 1];
            Encoding.ASCII.GetBytes(value, 0, value.Length, data, 0);

            PropertyItem property = image.PropertyItems[0];
            property.Id = id;
            property.Type = PropertyTagTypeAscii;
            property.Len = data.Length;
            property.Value = data;

            image.SetPropertyItem(property);
        }
Example #12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="src"></param>
 /// <param name="dst"></param>
 public static System.Drawing.Image Clone(System.Drawing.Image src, System.Drawing.Image dst)
 {
     if (src is System.Drawing.Image && dst is System.Drawing.Image)
     {
         if (ExifFormat.Contains(src.RawFormat) && ExifFormat.Contains(dst.RawFormat))
         {
             foreach (var item in src.PropertyItems)
             {
                 dst.SetPropertyItem(item);
             }
         }
     }
     return(dst);
 }
Example #13
0
        public static void SetPropertyItems(Image image, PropertyItem[] items)
        {
            PropertyItem[] pis = image.PropertyItems;

            foreach (PropertyItem pi in pis)
            {
                image.RemovePropertyItem(pi.Id);
            }

            foreach (PropertyItem pi in items)
            {
                image.SetPropertyItem(pi);
            }
        }
Example #14
0
 /// <summary>
 /// <para>Conserta a rotação da imagem de acordo com a rotação original.</para>
 /// <para>Algumas imagens "importadas" tem a orientação diferente da definida no arquivo, este método conserta.</para>
 /// </summary>
 /// <param name="self">Stream de imagem</param>
 public static void FixToOriginalOrientation(this System.Drawing.Image self)
 {
     foreach (var prop in self.PropertyItems)
     {
         if (prop.Id == 0x0112)
         {
             int            orientationValue = self.GetPropertyItem(prop.Id).Value[0];
             RotateFlipType rotateFlipType   = GetOrientationToFlipType(orientationValue);
             self.RotateFlip(rotateFlipType);
             prop.Value[0] = 1;
             self.SetPropertyItem(prop);
             break;
         }
     }
 }
Example #15
0
 private static void SetImageProperty(Image image, int propertyId, byte[] value)
 {
     var prop = (PropertyItem) FormatterServices.GetUninitializedObject(typeof(PropertyItem));
     prop.Id = propertyId;
     prop.Value = value;
     prop.Len = prop.Value.Length;
     prop.Type = 1;
     image.SetPropertyItem(prop);
 }
Example #16
0
        /// <summary>
        /// Saves image to stream with specified quality
        /// </summary>
        public static void SaveToStream(Image imageToSave, Stream stream, OutputFormat extension, int quality)
        {
            ImageFormat imfo = null;
            bool disposeImage = false;

            switch (extension) {
                case OutputFormat.bmp:
                    imfo = ImageFormat.Bmp;
                    break;
                case OutputFormat.gif:
                    imfo = ImageFormat.Gif;
                    break;
                case OutputFormat.jpg:
                    imfo = ImageFormat.Jpeg;
                    break;
                case OutputFormat.png:
                    imfo = ImageFormat.Png;
                    break;
                case OutputFormat.tiff:
                    imfo = ImageFormat.Tiff;
                    break;
                default:
                    imfo = ImageFormat.Png;
                    break;
            }
            // If Quantizing is enable, overwrite the image to save with a 256 - color version
            if (conf.OutputFileReduceColors) {
                try {
                    LOG.Debug("Reducing colors on bitmap.");
                    Quantizer quantizer = new OctreeQuantizer(255,8);
                    imageToSave = quantizer.Quantize(imageToSave);
                    // Make sure the "new" image is disposed
                    disposeImage = true;
                } catch(Exception e) {
                    LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e);
                }
            }

            try {
                // Create meta-data
                PropertyItem softwareUsedPropertyItem = CreatePropertyItem(PROPERTY_TAG_SOFTWARE_USED, "Greenshot");
                if (softwareUsedPropertyItem != null) {
                    try {
                        imageToSave.SetPropertyItem(softwareUsedPropertyItem);
                    } catch (ArgumentException) {
                        LOG.WarnFormat("Image of type {0} do not support property {1}", imfo, softwareUsedPropertyItem.Id);
                    }
                }
                LOG.DebugFormat("Saving image to stream with PixelFormat {0}", imageToSave.PixelFormat);
                if (imfo == ImageFormat.Jpeg) {
                    EncoderParameters parameters = new EncoderParameters(1);
                    parameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(Encoder.Quality, quality);
                    ImageCodecInfo[] ies = ImageCodecInfo.GetImageEncoders();
                    imageToSave.Save(stream, ies[1], parameters);
                } else {
                    imageToSave.Save(stream, imfo);
                }
            } finally {
                // cleanup if needed
                if (disposeImage && imageToSave != null) {
                    imageToSave.Dispose();
                }
            }
        }
Example #17
0
 /// <summary>
 /// Add the greenshot property!
 /// </summary>
 /// <param name="imageToSave"></param>
 private static void AddTag(Image imageToSave)
 {
     // Create meta-data
     PropertyItem softwareUsedPropertyItem = CreatePropertyItem(PROPERTY_TAG_SOFTWARE_USED, "Greenshot");
     if (softwareUsedPropertyItem != null)
     {
         try
         {
             imageToSave.SetPropertyItem(softwareUsedPropertyItem);
         }
         catch (Exception)
         {
             LOG.WarnFormat("Couldn't set property {0}", softwareUsedPropertyItem.Id);
         }
     }
 }
        /// <summary>
        /// Embed the data into given image in memory.
        /// NOTE: You will still need to save the image to disk yourself
        /// </summary>
        /// <param name="image">Image in memory in which to write the embedded data</param>
        /// <exception cref="System.Exception">Not all image data was given correctly.</exception>
        public void SaveToImage(Image image)
        {
            if (image.PropertyItems.Length == 0)
                throw new Exception("No property items detected on the given Image object.");

            PropertyItem tempPropItem = image.PropertyItems[0];
            byte[] b_Time = new byte[24];
            byte[] justOne = BitConverter.GetBytes(1);
            byte[] temp = BitConverter.GetBytes(GPSHours);
            Array.Copy(temp, 0, b_Time, 0, 4);
            Array.Copy(justOne, 0, b_Time, 4, 4);
            temp = BitConverter.GetBytes(GPSMinutes);
            Array.Copy(temp, 0, b_Time, 8, 4);
            Array.Copy(justOne, 0, b_Time, 12, 4);
            int[] frac = ConvertToFraction(GPSSeconds);
            Array.Copy(BitConverter.GetBytes(frac[0]), 0, b_Time, 16, 4);
            Array.Copy(BitConverter.GetBytes(frac[1]), 0, b_Time, 20, 4);
            tempPropItem.Id = (int)ProportyItemId.gpsTime;
            tempPropItem.Type = 5;
            tempPropItem.Len = b_Time.Length;
            tempPropItem.Value = b_Time;
            image.SetPropertyItem(tempPropItem);

            if (!String.IsNullOrEmpty(CameraModel))
            {
                byte[] byteoriginal = asciiEncoder.GetBytes(CameraModel);
                byte[] bytes = new byte[(byteoriginal.Length + 1)];
                Array.Copy(byteoriginal, 0, bytes, 0, byteoriginal.Length);
                bytes[(bytes.Length - 1)] = 0;
                tempPropItem.Id = (int)ProportyItemId.cameraModel;
                tempPropItem.Type = 2;
                tempPropItem.Len = bytes.Length;
                tempPropItem.Value = bytes;
                image.SetPropertyItem(tempPropItem);
            }

            byte[] latBytes = GetBytesGPSLatitude();
            tempPropItem.Id = (int)ProportyItemId.gpsLat;
            tempPropItem.Type = 5;
            tempPropItem.Len = latBytes.Length;
            tempPropItem.Value = latBytes;
            image.SetPropertyItem(tempPropItem);

            byte[] longBytes = GetBytesGPSLongitude();
            tempPropItem.Id = (int)ProportyItemId.gpsLong;
            tempPropItem.Type = 5;
            tempPropItem.Len = longBytes.Length;
            tempPropItem.Value = longBytes;
            image.SetPropertyItem(tempPropItem);

            byte[] b_AltRef = new byte[] { 0x0 };
            tempPropItem.Id = (int)ProportyItemId.gpsAltRef;
            tempPropItem.Type = 1;
            tempPropItem.Len = 1;
            tempPropItem.Value = b_AltRef;
            image.SetPropertyItem(tempPropItem);

            byte[] latRefBytes = new byte[2];
            latRefBytes[0] = asciiEncoder.GetBytes(GPSLatitudeRef)[0];
            tempPropItem.Id = (int)ProportyItemId.gpsLatRef;
            tempPropItem.Type = 2;
            tempPropItem.Len = latRefBytes.Length;
            tempPropItem.Value = latRefBytes;
            image.SetPropertyItem(tempPropItem);

            byte[] longRefBytes = new byte[2];
            longRefBytes[0] = asciiEncoder.GetBytes(GPSLongitudeRef)[0];
            tempPropItem.Id = (int)ProportyItemId.gpsLongRef;
            tempPropItem.Type = 2;
            tempPropItem.Len = longRefBytes.Length;
            tempPropItem.Value = longRefBytes;
            image.SetPropertyItem(tempPropItem);

            byte[] b_Heading = GetYAWBytes();
            tempPropItem.Id = (int)ProportyItemId.yaw;
            tempPropItem.Type = 5;
            tempPropItem.Len = b_Heading.Length;
            tempPropItem.Value = b_Heading;
            image.SetPropertyItem(tempPropItem);

            //tempPropItem = image.
            byte[] b_Alt = GetGPSAltBytes();
            tempPropItem.Id = (int)ProportyItemId.gpsAlt;
            tempPropItem.Type = 5;
            tempPropItem.Len = b_Alt.Length;
            tempPropItem.Value = b_Alt;
            image.SetPropertyItem(tempPropItem);
        }
Example #19
0
        /// <summary>
        /// Copies the EXIF data into the new image and adjusts the Width and Height 
        /// accordingly.
        /// </summary>
        /// <param name="oldImage"></param>
        /// <param name="newImage"></param>
        private static void CopyExif(Image oldImage, Image newImage)
        {
            foreach (PropertyItem property in oldImage.PropertyItems) {
                if (property.Id == EXIF_HEIGHT_ID) {
                    byte[] newHeight = BitConverter.GetBytes(newImage.Height);
                    property.Value = newHeight;
                } else if (property.Id == EXIF_WIDTH_ID) {
                    byte[] newWidth = BitConverter.GetBytes(newImage.Width);
                    property.Value = newWidth;
                }

                newImage.SetPropertyItem(property);
            }
        }
Example #20
0
        /// <summary>
        /// Adjusts the Date/Time of PropertyItem propDecId in Image photo with period timeShift
        /// </summary>
        /// <param name="photo"></param>
        /// <param name="propDecId"></param>
        /// <param name="timeShift"></param>
        private void ShiftPropItemDateTime(Image photo, int propDecId, TimeSpan timeShift, bool updateLog)
        {
            PropertyItem dateTimeItem = photo.GetPropertyItem(propDecId);

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

            string dateAsString = encoding.GetString(dateTimeItem.Value);
            dateAsString = dateAsString.Remove(19);
            DateTime tempDateTime = DateTime.ParseExact(dateAsString, "yyyy:MM:dd HH:mm:ss", null);
            tempDateTime += timeShift;
            dateAsString = tempDateTime.ToString("yyyy:MM:dd HH:mm:ss");
            if (updateLog) AddStatus(dateAsString);
            dateAsString += "\0";
            dateTimeItem.Value = encoding.GetBytes(dateAsString);
            photo.SetPropertyItem(dateTimeItem);
        }
Example #21
0
        /// <summary>
        /// Make sure the image is orientated correctly
        /// </summary>
        /// <param name="image"></param>
        public static void Orientate(Image image)
        {
            /*if (!conf.ProcessEXIFOrientation)
            {
                return;
            }*/
            try
            {
                // Get the index of the orientation property.
                int orientationIndex = Array.IndexOf(image.PropertyIdList, EXIF_ORIENTATION_ID);
                // If there is no such property, return Unknown.
                if (orientationIndex < 0)
                {
                    return;
                }
                PropertyItem item = image.GetPropertyItem(EXIF_ORIENTATION_ID);

                ExifOrientations orientation = (ExifOrientations)item.Value[0];
                // Orient the image.
                switch (orientation)
                {
                    case ExifOrientations.Unknown:
                    case ExifOrientations.TopLeft:
                        break;
                    case ExifOrientations.TopRight:
                        image.RotateFlip(RotateFlipType.RotateNoneFlipX);
                        break;
                    case ExifOrientations.BottomRight:
                        image.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        break;
                    case ExifOrientations.BottomLeft:
                        image.RotateFlip(RotateFlipType.RotateNoneFlipY);
                        break;
                    case ExifOrientations.LeftTop:
                        image.RotateFlip(RotateFlipType.Rotate90FlipX);
                        break;
                    case ExifOrientations.RightTop:
                        image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        break;
                    case ExifOrientations.RightBottom:
                        image.RotateFlip(RotateFlipType.Rotate90FlipY);
                        break;
                    case ExifOrientations.LeftBottom:
                        image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        break;
                }
                // Set the orientation to be normal, as we rotated the image.
                item.Value[0] = (byte)ExifOrientations.TopLeft;
                image.SetPropertyItem(item);
            }
            catch (Exception orientEx)
            {
                LOG.Warn("Problem orientating the image: ", orientEx);
            }
        }
Example #22
0
        public static void LoadProperties(Image dstImage, Document srcDoc)
        {
            Bitmap asBitmap = dstImage as Bitmap;

            if (asBitmap != null)
            {
                // Sometimes GDI+ does not honor the resolution tags that we
                // put in manually via the EXIF properties.
                float dpiX;
                float dpiY;

                switch (srcDoc.DpuUnit)
                {
                    case MeasurementUnit.Centimeter:
                        dpiX = (float)Document.DotsPerCmToDotsPerInch(srcDoc.DpuX);
                        dpiY = (float)Document.DotsPerCmToDotsPerInch(srcDoc.DpuY);
                        break;

                    case MeasurementUnit.Inch:
                        dpiX = (float)srcDoc.DpuX;
                        dpiY = (float)srcDoc.DpuY;
                        break;

                    default:
                    case MeasurementUnit.Pixel:
                        dpiX = 1.0f;
                        dpiY = 1.0f;
                        break;
                }

                try
                {
                    asBitmap.SetResolution(dpiX, dpiY);
                }

                catch (Exception)
                {
                    // Ignore error
                }
            }

            Metadata metaData = srcDoc.Metadata;

            foreach (string key in metaData.GetKeys(Metadata.ExifSectionName))
            {
                string blob = metaData.GetValue(Metadata.ExifSectionName, key);
                PropertyItem pi = PdnGraphics.DeserializePropertyItem(blob);

                try
                {
                    dstImage.SetPropertyItem(pi);
                }

                catch (ArgumentException)
                {
                    // Ignore error: the image does not support property items
                }
            }
        }
        /// <summary>
        /// Saves image to stream with specified quality
        /// </summary>
        public static void SaveToStream(Image imageToSave, Stream stream, OutputFormat extension, int quality, bool reduceColors)
        {
            ImageFormat imageFormat = null;
            bool disposeImage = false;

            switch (extension) {
                case OutputFormat.bmp:
                    imageFormat = ImageFormat.Bmp;
                    break;
                case OutputFormat.gif:
                    imageFormat = ImageFormat.Gif;
                    break;
                case OutputFormat.jpg:
                    imageFormat = ImageFormat.Jpeg;
                    break;
                case OutputFormat.png:
                    imageFormat = ImageFormat.Png;
                    break;
                case OutputFormat.tiff:
                    imageFormat = ImageFormat.Tiff;
                    break;
                default:
                    imageFormat = ImageFormat.Png;
                    break;
            }

            // Fix for Bug #3468436, force quantizing when output format is gif as this has only 256 colors!
            if (ImageFormat.Gif.Equals(imageFormat)) {
                reduceColors = true;
            }

            // Removing transparency if it's not supported
            if (imageFormat != ImageFormat.Png) {
                imageToSave = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb);
                disposeImage = true;
            }

            // check for color reduction, forced or automatically
            if (conf.OutputFileAutoReduceColors || reduceColors) {
                WuQuantizer quantizer = new WuQuantizer((Bitmap)imageToSave);
                int colorCount = quantizer.GetColorCount();
                LOG.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount);
                if (reduceColors || colorCount < 256) {
                    try {
                        LOG.Info("Reducing colors on bitmap to 255.");
                        Image tmpImage = quantizer.GetQuantizedImage(255);
                        if (disposeImage) {
                            imageToSave.Dispose();
                        }
                        imageToSave = tmpImage;
                        // Make sure the "new" image is disposed
                        disposeImage = true;
                    } catch (Exception e) {
                        LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e);
                    }
                }
            } else {
                LOG.Info("Skipping color reduction test, OutputFileAutoReduceColors is set to false.");
            }

            try {
                // Create meta-data
                PropertyItem softwareUsedPropertyItem = CreatePropertyItem(PROPERTY_TAG_SOFTWARE_USED, "Greenshot");
                if (softwareUsedPropertyItem != null) {
                    try {
                        imageToSave.SetPropertyItem(softwareUsedPropertyItem);
                    } catch (ArgumentException) {
                        LOG.WarnFormat("Image of type {0} do not support property {1}", imageFormat, softwareUsedPropertyItem.Id);
                    }
                }
                LOG.DebugFormat("Saving image to stream with Format {0} and PixelFormat {1}", imageFormat, imageToSave.PixelFormat);
                if (imageFormat == ImageFormat.Jpeg) {
                    EncoderParameters parameters = new EncoderParameters(1);
                    parameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(Encoder.Quality, quality);
                    ImageCodecInfo[] ies = ImageCodecInfo.GetImageEncoders();
                    imageToSave.Save(stream, ies[1], parameters);
                } else if (imageFormat != ImageFormat.Png && Image.IsAlphaPixelFormat(imageToSave.PixelFormat)) {
                    // No transparency in target format
                    using (Bitmap tmpBitmap = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb)) {
                        tmpBitmap.Save(stream, imageFormat);
                    }
                } else {
                    imageToSave.Save(stream, imageFormat);
                }
            } finally {
                // cleanup if needed
                if (disposeImage && imageToSave != null) {
                    imageToSave.Dispose();
                }
            }
        }
        /// <summary>
        /// Saves image to specific path with specified quality
        /// </summary>
        public static void Save(Image img, string fullPath, int quality)
        {
            // check whether path exists - if not create it
            DirectoryInfo di = new DirectoryInfo(fullPath.Substring(0, fullPath.LastIndexOf(Path.DirectorySeparatorChar)));
            if (!di.Exists)
            {
                Directory.CreateDirectory(di.FullName);
            }

            ImageFormat imfo = null;
            string extension = fullPath.Substring(fullPath.LastIndexOf(".") + 1);
            if (extension.Equals("jpg")) extension = "jpeg"; // we need jpeg string with e for reflection
            extension = extension.Substring(0, 1).ToUpper() + extension.Substring(1).ToLower();
            try
            {
                Type t = typeof(ImageFormat);
                PropertyInfo pi = t.GetProperty(extension, typeof(ImageFormat));
                imfo = (ImageFormat)pi.GetValue(null, null);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                MessageBox.Show("Could not use " + extension + " as image format. Using Jpeg.");
                imfo = ImageFormat.Jpeg;
                extension = imfo.ToString();
            }
            PropertyItem pit = PropertyItemProvider.GetPropertyItem(0x0131, "Greenshot");
            img.SetPropertyItem(pit);
            if (extension.Equals("Jpeg"))
            {
                EncoderParameters parameters = new EncoderParameters(1);
                parameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(Encoder.Quality, quality);
                ImageCodecInfo[] ies = ImageCodecInfo.GetImageEncoders();
                img.Save(fullPath, ies[1], parameters);
            }
            else
            {
                img.Save(fullPath, imfo);
            }
            if ((bool)AppConfig.GetInstance().Output_File_CopyPathToClipboard)
            {
                ido.SetData(DataFormats.Text, true, fullPath);
                Clipboard.SetDataObject(ido, true);
            }
        }
Example #25
0
 private static void CopyMetadata(PropertyItem[] properties, Image target) {
     foreach (PropertyItem property in properties) {
         try {
             target.SetPropertyItem(property);
         }
         catch (ArgumentException) {
             // just ignore it; on some configurations this fails
         }
     }
 }
Example #26
0
        //Add Watermark to photo.
        private System.Drawing.Image CreateWatermark(System.Drawing.Image imgPhoto, string Copyright)
        {
            Graphics g = Graphics.FromImage(imgPhoto);

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

            foreach (PropertyItem pItem in imgPhoto.PropertyItems)
            {
                imgPhoto.SetPropertyItem(pItem);
            }

            int phWidth  = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //create a Bitmap the Size of the original photograph
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //load the Bitmap into a Graphics object
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //------------------------------------------------------------
            //Step #1 - Insert Copyright message
            //------------------------------------------------------------

            //Set the rendering quality for this Graphics object
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //Draws the photo Image object at original size to the graphics object.
            grPhoto.DrawImage(
                imgPhoto,                               // Photo Image object
                new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                0,                                      // x-coordinate of the portion of the source image to draw.
                0,                                      // y-coordinate of the portion of the source image to draw.
                phWidth,                                // Width of the portion of the source image to draw.
                phHeight,                               // Height of the portion of the source image to draw.
                GraphicsUnit.Pixel);                    // Units of measure

            //-------------------------------------------------------
            //to maximize the size of the Copyright message we will
            //test multiple Font sizes to determine the largest posible
            //font we can use for the width of the Photograph
            //define an array of point sizes you would like to consider as possiblities
            //-------------------------------------------------------
            int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

            Font  crFont = null;
            SizeF crSize = new SizeF();

            //Loop through the defined sizes checking the length of the Copyright string
            //If its length in pixles is less then the image width choose this Font size.
            for (int i = 0; i < 7; i++)
            {
                //set a Font object to Arial (i)pt, Bold
                crFont = new Font("arial", sizes[i], FontStyle.Bold);
                //Measure the Copyright string in this Font
                crSize = grPhoto.MeasureString(Copyright, crFont);

                if ((ushort)crSize.Width < (ushort)phWidth)
                {
                    break;
                }
            }

            //Since all photographs will have varying heights, determine a
            //position 5% from the bottom of the image
            int yPixlesFromBottom = (int)(phHeight * .05);

            //Now that we have a point size use the Copyrights string height
            //to determine a y-coordinate to draw the string of the photograph
            float yPosFromBottom = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));

            //Determine its x-coordinate by calculating the center of the width of the image
            float xCenterOfImg = (phWidth / 2);

            //Define the text layout by setting the text alignment to centered
            StringFormat StrFormat = new StringFormat();

            StrFormat.Alignment = StringAlignment.Near;

            //define a Brush which is semi trasparent black (Alpha set to 153)
            SolidBrush semiTransBrush2 = new SolidBrush(System.Drawing.Color.FromArgb(153, 0, 0, 0));

            //Draw the Copyright string
            grPhoto.DrawString(Copyright,                                        //string of text
                               crFont,                                           //font
                               semiTransBrush2,                                  //Brush
                               new PointF(xCenterOfImg + 1, yPosFromBottom + 1), //Position
                               StrFormat);

            //define a Brush which is semi trasparent white (Alpha set to 153)
            SolidBrush semiTransBrush = new SolidBrush(System.Drawing.Color.FromArgb(153, 255, 255, 255));

            //Draw the Copyright string a second time to create a shadow effect
            //Make sure to move this text 1 pixel to the right and down 1 pixel
            grPhoto.DrawString(Copyright,                                //string of text
                               crFont,                                   //font
                               semiTransBrush,                           //Brush
                               new PointF(xCenterOfImg, yPosFromBottom), //Position
                               StrFormat);                               //Text alignment
            imgPhoto = bmPhoto;
            return(imgPhoto);
        }
Example #27
0
 public static void CopyMetadata(Image fromImage, Image toImage)
 {
     PropertyItem[] propertyItems = fromImage.PropertyItems;
     foreach (PropertyItem pi in propertyItems)
     {
         try
         {
             toImage.SetPropertyItem(pi);
         }
         catch (Exception e)
         {
             DebugHelper.WriteException(e);
         }
     }
 }
Example #28
0
 private static void CopyProperties(Image from, Image to)
 {
     foreach (var propertyItem in from.PropertyItems)
         to.SetPropertyItem(propertyItem);
 }