Esempio n. 1
0
        /// <summary>
        /// When publishing a video, this will create the image that put in the placeholder spot for the video.
        /// </summary>
        /// <param name="message">A message that will be drawn on the image</param>
        /// <returns></returns>
        private Bitmap CreateMockPlayer(string message)
        {
            // Draw the status on the image
            Bitmap img = ImageHelper2.CreateResizedBitmap(ResourceHelper.LoadAssemblyResourceBitmap("Video.Images.MockPlayer.png"),
                                                          HtmlSize.Width,
                                                          HtmlSize.Height,
                                                          ImageFormat.Png);

            try
            {
                using (Graphics g = Graphics.FromImage(img))
                {
                    BidiGraphics bidiGraphics = new BidiGraphics(g, img.Size);
                    if (VideoHasError())
                    {
                        DrawErrorMockPlayer(img, bidiGraphics, message);
                    }
                    else
                    {
                        DrawStatusMockPlayer(img, bidiGraphics, message);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error while creating a placeholder for a video: " + ex);
                return(null);
            }

            return(img);
        }
Esempio n. 2
0
        /// <summary>
        /// Creates an embedded shadow copy of a source image file.
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="fileService"></param>
        private void CreateShadowFile(ImageFileData sourceFile, ISupportingFileService fileService)
        {
            Size shadowSize = new Size(1280, 960);

            using (MemoryStream shadowStream = new MemoryStream())
            {
                ImageFormat format;
                string      fileExt;
                ImageHelper2.GetImageFormat(sourceFile.SupportingFile.FileName, out fileExt, out format);
                using (Bitmap sourceImage = new Bitmap(sourceFile.Uri.LocalPath))
                {
                    if (sourceImage.Width > shadowSize.Width || sourceImage.Height > shadowSize.Height)
                    {
                        shadowSize = ImageHelper2.SaveScaledThumbnailImage(Math.Min(shadowSize.Width, sourceImage.Width),
                                                                           Math.Min(shadowSize.Height, sourceImage.Height),
                                                                           sourceImage, format, shadowStream);
                    }
                    else
                    {
                        shadowSize = sourceImage.Size;
                        using (FileStream fs = File.OpenRead(sourceFile.Uri.LocalPath))
                        {
                            StreamHelper.Transfer(fs, shadowStream);
                        }
                    }
                }
                shadowStream.Seek(0, SeekOrigin.Begin);

                ISupportingFile supportingFile = fileService.CreateSupportingFile(sourceFile.SupportingFile.FileName, shadowStream);
                _imageSourceShadowFile = new ImageFileData(supportingFile, shadowSize.Width, shadowSize.Height, ImageFileRelationship.SourceShadow);
            }
        }
Esempio n. 3
0
 public static Size WriteImageToFile(string sourceFile, int width, int height, string outputFile, bool preserveConstraints)
 {
     using (Bitmap sourceImage = new Bitmap(sourceFile))
     {
         FixImageOrientation(sourceImage);
         using (Stream imageOut = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
         {
             ImageFormat format;
             string      fileExt;
             ImageHelper2.GetImageFormat(sourceFile, out fileExt, out format);
             if (preserveConstraints)
             {
                 ImageHelper2.SaveScaledThumbnailImage(width, height, sourceImage, format, imageOut);
             }
             else
             {
                 ImageHelper2.SaveThumbnailImage(width, height, sourceImage, format, imageOut);
             }
         }
     }
     if (preserveConstraints)
     {
         using (Bitmap img = new Bitmap(outputFile))
             return(img.Size);
     }
     else
     {
         return(new Size(width, height));
     }
 }
        public override bool IsEditableEmbeddedImage()
        {
            if (!IsEmbeddedImage())
            {
                return(false);
            }

            string path = _imageData.GetImageSourceFile().Uri.LocalPath;

            if (ImageHelper2.IsAnimated(path))
            {
                return(false);
            }

            return(!ImageHelper2.IsMetafile(path));
        }
Esempio n. 5
0
        private string writeImage(Bitmap image, string srcFileName, string suffix, ImageFilter filter, CreateFileCallback createFileCallback)
        {
            string extension = Path.GetExtension(srcFileName).ToLower(CultureInfo.InvariantCulture);

            srcFileName = Path.GetFileNameWithoutExtension(srcFileName) + suffix + extension;
            try
            {
                //save the thumbnail to disk
                ImageFormat imageFormat;
                ImageHelper2.GetImageFormat(srcFileName, out extension, out imageFormat);
                string filename = createFileCallback(Path.GetFileNameWithoutExtension(srcFileName) + extension);
                try
                {
                    if (filter != null)
                    {
                        image = filter(image);
                    }

                    using (FileStream fs = new FileStream(filename, FileMode.Create))
                    {
                        ImageHelper2.SaveImage(image, imageFormat, fs);
                    }
                    return(filename);
                }
                catch (Exception e)
                {
                    Trace.Fail("Failed to save image as format " + imageFormat.Guid + ": " + e.ToString());

                    //try to fall back to generating a PNG version of the image
                    imageFormat = ImageFormat.Png;
                    extension   = ".png";
                    filename    = createFileCallback(Path.GetFileNameWithoutExtension(srcFileName) + extension);

                    using (FileStream fs = new FileStream(filename, FileMode.Create))
                    {
                        ImageHelper2.SaveImage(image, ImageFormat.Png, fs);
                    }
                    return(filename);
                }
            }
            catch (Exception e)
            {
                Trace.Fail("Error while trying to create thumbnail: " + e.Message, e.StackTrace);
                throw;
            }
        }
        public void Decorate(ImageDecoratorContext context)
        {
            CropDecoratorSettings settings = new CropDecoratorSettings(context.Settings);
            //ImageUtils.AdjustBrightness(bsettings.Brightness, bsettings.Contrast, context.Image);
            Rectangle?rect = settings.CropRectangle;

            // only do the following if polaroid is active
            if (context.EnforcedAspectRatio != null)
            {
                float          aspectRatio = context.EnforcedAspectRatio.Value;
                RotateFlipType flip;
                if (context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert ||
                    context.InvocationSource == ImageDecoratorInvocationSource.Reset)
                {
                    flip = ImageUtils.GetFixupRotateFlipFromExifOrientation(context.Image);
                }
                else
                {
                    flip = context.ImageRotation;
                }
                if (ImageUtils.IsRotated90(flip))
                {
                    aspectRatio = 1 / aspectRatio;
                }

                rect = RectangleHelper.EnforceAspectRatio(rect ?? new Rectangle(Point.Empty, context.Image.Size), aspectRatio);
            }

            if (rect != null)
            {
                Bitmap cropped = ImageHelper2.CropBitmap(context.Image, (Rectangle)rect);
                try
                {
                    PropertyItem orientation = context.Image.GetPropertyItem(0x112);
                    if (orientation != null)
                    {
                        cropped.SetPropertyItem(orientation);
                    }
                }
                catch (ArgumentException)
                {
                    // orientation data was not present
                }
                context.Image = cropped;
            }
        }
Esempio n. 7
0
        void ISupportingFiles.AddImage(string fileName, Image image, ImageFormat imageFormat)
        {
            // convert the bitmap into a stream
            using (MemoryStream imageStream = new MemoryStream())
            {
                // save the image into the strea
                if (image is Bitmap)
                {
                    ImageHelper2.SaveImage((Bitmap)image, imageFormat, imageStream);
                }
                else
                {
                    image.Save(imageStream, imageFormat);
                }

                // add the stream to the supporting file
                imageStream.Seek(0, SeekOrigin.Begin);
                _extensionData.AddFile(fileName, imageStream);
            }
        }
Esempio n. 8
0
        public Bitmap ApplyImageDecorators(Bitmap bitmap)
        {
            _currImage     = bitmap;
            _originalImage = bitmap;

            bool borderNeedsReset = true;

            foreach (ImageDecorator decorator in _decoratorsList)
            {
                ApplyImageDecorator(decorator, _currImage, ref borderNeedsReset);
            }

            //update the rotation and size info in the image properties
            if (_embedType == ImageEmbedType.Embedded)
            {
//                if (borderNeedsReset)
//                    BorderMargin = ImageBorderMargin.Empty;

                if (!ImageHelper2.IsAnimated(_currImage))
                {
                    Size currImageSize = _currImage.Size;

                    //update the inline image size (don't forget to remove size added by borders)
                    ImageBorderMargin borderMargin = BorderMargin;
                    Size borderlessImageSize       = new Size(
                        currImageSize.Width - borderMargin.Width,
                        currImageSize.Height - borderMargin.Height);
                    _imageInfo.InlineImageSize = borderlessImageSize;
                }
            }
            else
            {
                _imageInfo.LinkTargetImageSize = _currImage.Size;
            }

            _originalImage = null;
            return(_currImage);
        }
Esempio n. 9
0
        internal static Bitmap ResizeImage(Bitmap image, Size newSize, RotateFlipType rotation)
        {
            if (rotation != RotateFlipType.RotateNoneFlipNone)
            {
                image.RotateFlip(rotation);
                image = new Bitmap(image);
            }

            int newWidth  = Math.Max(newSize.Width, 2);
            int newHeight = Math.Max(newSize.Height, 2);

            //resize the image (if its not already the correct size!)
            Bitmap bitmap;

            if (image.Width != newWidth || image.Height != newHeight)
            {
                bitmap = ImageHelper2.CreateResizedBitmap(image, newWidth, newHeight, image.RawFormat);
            }
            else
            {
                bitmap = image;
            }
            return(bitmap);
        }
Esempio n. 10
0
        public void Decorate(ImageDecoratorContext context)
        {
            bool useOriginalImage = true;
            HtmlImageResizeDecoratorSettings settings = new HtmlImageResizeDecoratorSettings(context.Settings, context.ImgElement);

            if (context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert ||
                context.InvocationSource == ImageDecoratorInvocationSource.Reset)
            {
                // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                // decorator settings.
                // If ImageSizeName is set, then use that instead of default values
                if (settings.IsImageSizeNameSet && context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert)
                {
                    // We must be copying settings from another instance of the same image
                    settings.SetImageSize(settings.ImageSize, settings.ImageSizeName);

                    // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                    // decorator settings.
                    // Also if we are copying settings, then use the image instance from context instead of the
                    // original image. This ensures we use the cropped image (if any) to resize.
                    useOriginalImage = false;
                }
                else
                {
                    //calculate the default image size and rotation.  If the camera has indicated that the
                    //orientation of the photo is rotated (in the EXIF data), shift the rotation appropriately
                    //to insert the image correctly.

                    //Fix the image orientation based on the Exif data (added by digital cameras).
                    RotateFlipType fixedRotation = ImageUtils.GetFixupRotateFlipFromExifOrientation(context.Image);
                    settings.Rotation = fixedRotation;

                    settings.BaseSize = context.Image.Size;

                    //the default size is a scaled version of the image based on the default inline size constraints.
                    Size defaultBoundsSize;
                    if (settings.DefaultBoundsSizeName != ImageSizeName.Full)
                    {
                        defaultBoundsSize = settings.DefaultBoundsSize;
                    }
                    else //original size is default, so we aren't going to scale
                    {
                        defaultBoundsSize = context.Image.Size;
                    }
                    //calulate the base image size to scale from.  If the image is rotated 90 degrees, then switch the height/width
                    Size baseImageSize = context.Image.Size;
                    if (ImageUtils.IsRotated90(settings.Rotation))
                    {
                        baseImageSize = new Size(baseImageSize.Height, baseImageSize.Width);
                    }

                    //calculate and set the scaled default size using the defaultSizeBounds
                    //Note: if the image dimensions are smaller than the default, don't scale that dimension (bug 419446)
                    Size defaultSize =
                        ImageUtils.GetScaledImageSize(Math.Min(baseImageSize.Width, defaultBoundsSize.Width),
                                                      Math.Min(baseImageSize.Height, defaultBoundsSize.Height),
                                                      baseImageSize);
                    if (defaultSize.Width < defaultBoundsSize.Width && defaultSize.Height < defaultBoundsSize.Height)
                    {
                        settings.SetImageSize(defaultSize, ImageSizeName.Full);
                    }
                    else
                    {
                        settings.SetImageSize(defaultSize, settings.DefaultBoundsSizeName);
                    }
                }
            }
            else if (settings.BaseSizeChanged(context.Image))
            {
                Size newBaseSize = context.Image.Size;
                settings.SetImageSize(AdjustImageSizeForNewBaseSize(true, settings, newBaseSize, settings.Rotation, context), null);
                settings.BaseSize = newBaseSize;
            }

            //this decorator only applies to embedded images.
            if (context.ImageEmbedType == ImageEmbedType.Embedded && !ImageHelper2.IsAnimated(context.Image))
            {
                Bitmap imageToResize = null;

                // To make image insertion faster, we've already created an initial resized image on a background thread.
                if (context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert && useOriginalImage)
                {
                    try
                    {
                        string imageSrc = context.ImgElement.getAttribute("src", 2) as string;
                        if (!string.IsNullOrEmpty(imageSrc) && (UrlHelper.IsFileUrl(imageSrc) || File.Exists(new Uri(imageSrc).ToString())))
                        {
                            Uri imageSrcUri = new Uri(imageSrc);
                            imageToResize = (Bitmap)Image.FromFile(imageSrcUri.LocalPath);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.Write("Failed to load pre-created initial image: " + e);
                    }
                }

                if (imageToResize == null)
                {
                    imageToResize = context.Image;
                }

                // Figure the desired image size by taking the size of the img element
                // and calculate what borderless image size we'd need to start with
                // to end up at that size. This is different than simply subtracting
                // the existing border size, since borders can be relative to the
                // size of the base image.
                Size desiredImageSize = settings.BorderMargin.ReverseCalculateImageSize(settings.ImageSizeWithBorder);

                //resize the image and update the image used by the context.
                if (desiredImageSize != imageToResize.Size || settings.Rotation != RotateFlipType.RotateNoneFlipNone)
                {
                    context.Image = ResizeImage(imageToResize, desiredImageSize, settings.Rotation);
                }
                else
                {
                    context.Image = imageToResize;
                }

                if (settings.ImageSize != context.Image.Size)
                {
                    settings.SetImageSize(context.Image.Size, settings.ImageSizeName);
                }
            }
        }
Esempio n. 11
0
        private static List <NewImageInfo> ScanImages(IBlogPostHtmlEditor currentEditor, IEditorAccount editorAccount, ContentEditor editor, bool useDefaultTargetSettings)
        {
            List <NewImageInfo> newImages = new List <NewImageInfo>();

            ApplicationPerformance.ClearEvent("InsertImage");
            ApplicationPerformance.StartEvent("InsertImage");

            using (new WaitCursor())
            {
                IHTMLElement2 postBodyElement = (IHTMLElement2)((BlogPostHtmlEditorControl)currentEditor).PostBodyElement;
                if (postBodyElement != null)
                {
                    foreach (IHTMLElement imgElement in postBodyElement.getElementsByTagName("img"))
                    {
                        string imageSrc = imgElement.getAttribute("srcDelay", 2) as string;

                        if (string.IsNullOrEmpty(imageSrc))
                        {
                            imageSrc = imgElement.getAttribute("src", 2) as string;
                        }

                        // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                        // decorator settings. "wlCopySrcUrl" is inserted while copy/pasting within canvas.
                        bool   copyDecoratorSettings = false;
                        string attributeCopySrcUrl   = imgElement.getAttribute("wlCopySrcUrl", 2) as string;
                        if (!string.IsNullOrEmpty(attributeCopySrcUrl))
                        {
                            copyDecoratorSettings = true;
                            imgElement.removeAttribute("wlCopySrcUrl", 0);
                        }

                        // Check if we need to apply default values for image decorators
                        bool   applyDefaultDecorator       = true;
                        string attributeNoDefaultDecorator = imgElement.getAttribute("wlNoDefaultDecorator", 2) as string;
                        if (!string.IsNullOrEmpty(attributeNoDefaultDecorator) && string.Compare(attributeNoDefaultDecorator, "TRUE", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            applyDefaultDecorator = false;
                            imgElement.removeAttribute("wlNoDefaultDecorator", 0);
                        }

                        string applyDefaultMargins = imgElement.getAttribute("wlApplyDefaultMargins", 2) as string;
                        if (!String.IsNullOrEmpty(applyDefaultMargins))
                        {
                            DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager);
                            MarginStyle          defaultMargin        = defaultImageSettings.GetDefaultImageMargin();
                            // Now apply it to the image
                            imgElement.style.marginTop    = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Top);
                            imgElement.style.marginLeft   = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Left);
                            imgElement.style.marginBottom = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Bottom);
                            imgElement.style.marginRight  = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Right);
                            imgElement.removeAttribute("wlApplyDefaultMargins", 0);
                        }

                        if ((UrlHelper.IsFileUrl(imageSrc) || IsFullPath(imageSrc)) && !ContentSourceManager.IsSmartContent(imgElement))
                        {
                            Uri imageSrcUri = new Uri(imageSrc);
                            try
                            {
                                BlogPostImageData imageData = BlogPostImageDataList.LookupImageDataByInlineUri(editor.ImageList, imageSrcUri);
                                Emoticon          emoticon  = EmoticonsManager.GetEmoticon(imgElement);
                                if (imageData == null && emoticon != null)
                                {
                                    // This is usually an emoticon copy/paste and needs to be cleaned up.
                                    Uri inlineImageUri = editor.EmoticonsManager.GetInlineImageUri(emoticon);
                                    imgElement.setAttribute("src", UrlHelper.SafeToAbsoluteUri(inlineImageUri), 0);
                                }
                                else if (imageData == null)
                                {
                                    if (!File.Exists(imageSrcUri.LocalPath))
                                    {
                                        throw new FileNotFoundException(imageSrcUri.LocalPath);
                                    }

                                    // WinLive 188841: Manually attach the behavior so that the image cannot be selected or resized while its loading.
                                    DisabledImageElementBehavior disabledImageBehavior = new DisabledImageElementBehavior(editor.IHtmlEditorComponentContext);
                                    disabledImageBehavior.AttachToElement(imgElement);

                                    Size sourceImageSize                      = ImageUtils.GetImageSize(imageSrcUri.LocalPath);
                                    ImagePropertiesInfo  imageInfo            = new ImagePropertiesInfo(imageSrcUri, sourceImageSize, new ImageDecoratorsList(editor.DecoratorsManager, new BlogPostSettingsBag()));
                                    DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager);

                                    // Make sure this is set because some imageInfo properties depend on it.
                                    imageInfo.ImgElement = imgElement;

                                    bool isMetafile = ImageHelper2.IsMetafile(imageSrcUri.LocalPath);
                                    ImageClassification imgClass = ImageHelper2.Classify(imageSrcUri.LocalPath);
                                    if (!isMetafile && ((imgClass & ImageClassification.AnimatedGif) != ImageClassification.AnimatedGif))
                                    {
                                        // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                                        // decorator settings.
                                        if (copyDecoratorSettings)
                                        {
                                            // Try to look up the original copied source image.
                                            BlogPostImageData imageDataOriginal = BlogPostImageDataList.LookupImageDataByInlineUri(editor.ImageList, new Uri(attributeCopySrcUrl));
                                            if (imageDataOriginal != null && imageDataOriginal.GetImageSourceFile() != null)
                                            {
                                                // We have the original image reference, so lets make a clone of it.
                                                BlogPostSettingsBag originalBag            = (BlogPostSettingsBag)imageDataOriginal.ImageDecoratorSettings.Clone();
                                                ImageDecoratorsList originalDecoratorsList = new ImageDecoratorsList(editor.DecoratorsManager, originalBag);

                                                ImageFileData originalImageFileData = imageDataOriginal.GetImageSourceFile();
                                                Size          originalImageSize     = new Size(originalImageFileData.Width, originalImageFileData.Height);
                                                imageInfo = new ImagePropertiesInfo(originalImageFileData.Uri, originalImageSize, originalDecoratorsList);
                                            }
                                            else
                                            {
                                                // There are probably decorators applied to the image, but in a different editor so we can't access them.
                                                // We probably don't want to apply any decorators to this image, so apply blank decorators and load the
                                                // image as full size so it looks like it did before.
                                                imageInfo.ImageDecorators     = defaultImageSettings.LoadBlankLocalImageDecoratorsList();
                                                imageInfo.InlineImageSizeName = ImageSizeName.Full;
                                            }
                                        }
                                        else if (applyDefaultDecorator)
                                        {
                                            imageInfo.ImageDecorators = defaultImageSettings.LoadDefaultImageDecoratorsList();

                                            if ((imgClass & ImageClassification.TransparentGif) == ImageClassification.TransparentGif)
                                            {
                                                imageInfo.ImageDecorators.AddDecorator(NoBorderDecorator.Id);
                                            }
                                        }
                                        else
                                        {
                                            // Don't use default values for decorators
                                            imageInfo.ImageDecorators     = defaultImageSettings.LoadBlankLocalImageDecoratorsList();
                                            imageInfo.InlineImageSizeName = ImageSizeName.Full;
                                        }
                                    }
                                    else
                                    {
                                        ImageDecoratorsList decorators = new ImageDecoratorsList(editor.DecoratorsManager, new BlogPostSettingsBag());
                                        decorators.AddDecorator(editor.DecoratorsManager.GetDefaultRemoteImageDecorators());
                                        imageInfo.ImageDecorators = decorators;
                                    }

                                    imageInfo.ImgElement       = imgElement;
                                    imageInfo.DhtmlImageViewer = editorAccount.EditorOptions.DhtmlImageViewer;

                                    //discover the "natural" target settings from the DOM
                                    string linkTargetUrl = imageInfo.LinkTargetUrl;
                                    if (linkTargetUrl == imageSrc)
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.IMAGE;
                                    }
                                    else if (!String.IsNullOrEmpty(linkTargetUrl) && !UrlHelper.IsFileUrl(linkTargetUrl))
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.URL;
                                    }
                                    else
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.NONE;
                                    }

                                    if (useDefaultTargetSettings)
                                    {
                                        if (!GlobalEditorOptions.SupportsFeature(ContentEditorFeature.SupportsImageClickThroughs) && imageInfo.DefaultLinkTarget == LinkTargetType.IMAGE)
                                        {
                                            imageInfo.DefaultLinkTarget = LinkTargetType.NONE;
                                        }

                                        if (imageInfo.LinkTarget == LinkTargetType.NONE)
                                        {
                                            imageInfo.LinkTarget = imageInfo.DefaultLinkTarget;
                                        }
                                        if (imageInfo.DefaultLinkOptions.ShowInNewWindow)
                                        {
                                            imageInfo.LinkOptions.ShowInNewWindow = true;
                                        }
                                        imageInfo.LinkOptions.UseImageViewer       = imageInfo.DefaultLinkOptions.UseImageViewer;
                                        imageInfo.LinkOptions.ImageViewerGroupName = imageInfo.DefaultLinkOptions.ImageViewerGroupName;
                                    }

                                    Size defaultImageSize = defaultImageSettings.GetDefaultInlineImageSize();
                                    Size initialSize      = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, sourceImageSize);

                                    // add to list of new images
                                    newImages.Add(new NewImageInfo(imageInfo, imgElement, initialSize, disabledImageBehavior));
                                }
                                else
                                {
                                    // When switching blogs, try to adapt image viewer settings according to the blog settings.

                                    ImagePropertiesInfo imageInfo = new ImagePropertiesInfo(imageSrcUri, ImageUtils.GetImageSize(imageSrcUri.LocalPath), new ImageDecoratorsList(editor.DecoratorsManager, imageData.ImageDecoratorSettings));
                                    imageInfo.ImgElement = imgElement;
                                    // Make sure the new crop and tilt decorators get loaded
                                    imageInfo.ImageDecorators.MergeDecorators(DefaultImageSettings.GetImplicitLocalImageDecorators());
                                    string viewer = imageInfo.DhtmlImageViewer;
                                    if (viewer != editorAccount.EditorOptions.DhtmlImageViewer)
                                    {
                                        imageInfo.DhtmlImageViewer = editorAccount.EditorOptions.DhtmlImageViewer;
                                        imageInfo.LinkOptions      = imageInfo.DefaultLinkOptions;
                                    }

                                    // If the image is an emoticon, update the EmoticonsManager with the image's uri so that duplicate emoticons can point to the same file.
                                    if (emoticon != null)
                                    {
                                        editor.EmoticonsManager.SetInlineImageUri(emoticon, imageData.InlineImageFile.Uri);
                                    }
                                }
                            }
                            catch (ArgumentException e)
                            {
                                Trace.WriteLine("Could not initialize image: " + imageSrc);
                                Trace.WriteLine(e.ToString());
                            }
                            catch (DirectoryNotFoundException)
                            {
                                Debug.WriteLine("Image file does not exist: " + imageSrc);
                            }
                            catch (FileNotFoundException)
                            {
                                Debug.WriteLine("Image file does not exist: " + imageSrc);
                            }
                            catch (IOException e)
                            {
                                Debug.WriteLine("Image file cannot be read: " + imageSrc + " " + e);
                                DisplayMessage.Show(MessageId.FileInUse, imageSrc);
                            }
                        }
                    }
                }
            }

            return(newImages);
        }
Esempio n. 12
0
        /// <summary>
        /// Inserts a set of images into the current editor, optionally assigning each image an id.
        /// </summary>
        /// <param name="imagePaths">paths of the images to insert</param>
        internal static void InsertImagesCore(IBlogPostHtmlEditor currentEditor, ISupportingFileService fileService, IEditorAccount editorAccount, OpenLiveWriter.PostEditor.ContentEditor editor, string[] imagePaths)
        {
            using (OpenLiveWriter.PostEditor.ContentEditor.EditorUndoUnit undo = new OpenLiveWriter.PostEditor.ContentEditor.EditorUndoUnit(currentEditor))
            {
                StringBuilder htmlBuilder = new StringBuilder();

                //calculate the size for inserted images (based on the user's saved default for this blog)
                DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager);
                Size defaultImageSize = defaultImageSettings.GetDefaultInlineImageSize();

                //Generate the default img HTML for the image paths.  Initially, the images are linked to the source image
                //path so that the DOM version of the HTML can be loaded.  Once the images are loaded into the DOM, we can apply
                //the image decorators to generate scaled images, borders, etc.
                ImagePropertiesInfo[] imageInfos = new ImagePropertiesInfo[imagePaths.Length];

                // don't insert into the title
                currentEditor.FocusBody();

                for (int i = 0; i < imageInfos.Length; i++)
                {
                    string imagePath = imagePaths[i];

                    Uri imgUri;
                    if (UrlHelper.IsUrl(imagePath))
                    {
                        imgUri = new Uri(imagePath);
                    }
                    else
                    {
                        imgUri = new Uri(UrlHelper.CreateUrlFromPath(imagePath));
                    }

                    Size imageSize = new Size(1, 1);
                    if (imgUri.IsFile && File.Exists(imagePath))
                    {
                        if (!File.Exists(imgUri.LocalPath))
                        {
                            Trace.Fail("Error inserting image - the image URL was corrupted: " + imagePath);
                        }
                        else
                        {
                            try
                            {
                                //check the validity of the image file
                                imageSize = ImageUtils.GetImageSize(imagePath);
                            }
                            catch (Exception)
                            {
                                Trace.WriteLine("There is a problem with the image file: " + imagePath);

                                // Insert anyway, MSHTML will show a red X in place of the image.
                                htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imgUri)));

                                continue;
                            }
                        }
                    }

                    // If the image has an embedded thumbnail, we'll use it as a place holder for the <img src="...">
                    // until we generate an inline image and apply decorators.
                    Stream embeddedThumbnailStream = ImageHelper2.GetEmbeddedThumbnailStream(imagePath);

                    if (embeddedThumbnailStream != null)
                    {
                        // Save thumbnail to disk.
                        ISupportingFile imageFileEmbeddedThumbnail = fileService.CreateSupportingFile(Path.GetFileName(imagePath), Guid.NewGuid().ToString(), embeddedThumbnailStream);

                        imageSize = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, imageSize);
                        //insert the default image html
                        String imageElementAttrs = String.Format(CultureInfo.InvariantCulture, " width=\"{0}\" height=\"{1}\"", imageSize.Width, imageSize.Height);

                        htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" srcDelay=\"{1}\" {2} />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imageFileEmbeddedThumbnail.FileUri)), HtmlUtils.EscapeEntities(imgUri.ToString()), imageElementAttrs);
                    }
                    else if (currentEditor is BlogPostHtmlEditorControl && (imagePaths.Length > DELAYED_IMAGE_THRESHOLD || imageSize.Width * imageSize.Height > 16777216 /*4096 X 4096*/))
                    {
                        // If we are using a delayed loading tactic then we insert using the srcdelay
                        htmlBuilder.Append(MakeHtmlForImageSourceDelay(imgUri.ToString()));
                    }
                    else
                    {
                        imageSize = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, imageSize);
                        //insert the default image html
                        String imageElementAttrs = imgUri.IsFile ? String.Format(CultureInfo.InvariantCulture, " width=\"{0}\" height=\"{1}\"", imageSize.Width, imageSize.Height) : String.Empty;

                        htmlBuilder.AppendFormat(CultureInfo.InvariantCulture, "<img src=\"{0}\" {1} />", HtmlUtils.EscapeEntities(UrlHelper.SafeToAbsoluteUri(imgUri)), imageElementAttrs);
                    }
                }

                //insert the HTML into the editor
                currentEditor.InsertHtml(htmlBuilder.ToString(), false);

                selectionChanged = false;
                BlogPostHtmlEditorControl blogPostEditor = currentEditor as BlogPostHtmlEditorControl;
                if (blogPostEditor != null)
                {
                    blogPostEditor.SelectionChanged += blogPostEditor_SelectionChanged;
                }

                //now that the image HTML is inserted into the editor, apply the default settings to the new images.
                undo.Commit();
            }
        }
Esempio n. 13
0
        private void SetPreviewPicture(Bitmap image, string filename)
        {
            int    maxWidth      = _previewBox.Width - 2;
            int    maxHeight     = _previewBox.Height - 2;
            bool   scaled        = true;
            int    currentWidth  = image.Width;
            int    currentHeight = image.Height;
            double ratio         = 1.00;

            //if height and width are too big
            if (currentWidth > maxWidth && currentHeight > maxHeight)
            {
                //size according to the one that is more off of the available area
                if ((maxWidth / currentWidth) < (maxHeight / currentHeight))
                {
                    ratio = (double)maxWidth / (double)currentWidth;
                }
                else
                {
                    ratio = (double)maxHeight / (double)currentHeight;
                }
            }
            //if just width
            else if (currentWidth > maxWidth)
            {
                ratio = (double)maxWidth / (double)currentWidth;
            }
            //if just height
            else if (currentHeight > maxHeight)
            {
                ratio = (double)maxHeight / (double)currentHeight;
            }
            //else fine
            else
            {
                scaled = false;
            }

            ImageFormat format;
            string      fileExt;

            ImageHelper2.GetImageFormat(filename, out fileExt, out format);
            int newWidth  = (int)(currentWidth * ratio);
            int newHeight = (int)(currentHeight * ratio);

            Bitmap newImage = ImageHelper2.CreateResizedBitmap(image, newWidth, newHeight, format);

            //if image is small enough, add border
            if (newWidth <= maxWidth && newHeight <= maxHeight)
            {
                Bitmap borderPic = new Bitmap(newWidth + 2, newHeight + 2);
                //Get a graphics object for it
                using (Graphics g = Graphics.FromImage(borderPic))
                {
                    g.TextRenderingHint = TextRenderingHint.AntiAlias;

                    int   R    = SystemColors.Control.R;
                    int   G    = SystemColors.Control.G;
                    int   B    = SystemColors.Control.B;
                    Color dark = Color.FromArgb((int)(R * 0.9), (int)(G * 0.9), (int)(B * 0.9));
                    //draw the border
                    g.FillRectangle(new SolidBrush(dark), new Rectangle(0, 0, borderPic.Width, 1));
                    g.FillRectangle(new SolidBrush(dark), new Rectangle(0, borderPic.Height - 1, borderPic.Width, 1));
                    g.FillRectangle(new SolidBrush(dark), new Rectangle(0, 0, 1, borderPic.Height));
                    g.FillRectangle(new SolidBrush(dark), new Rectangle(borderPic.Width - 1, 0, 1, borderPic.Height));

                    //draw our image back in the middle
                    g.DrawImage(newImage, new Rectangle(1, 1, newWidth, newHeight), 0, 0, newWidth, newHeight, GraphicsUnit.Pixel);
                }
                _previewBox.Image = borderPic;
            }
            else
            {
                _previewBox.Image = newImage;
            }

            string picsize;

            if (!scaled)
            {
                picsize = MakeDimensions(currentWidth, currentHeight);
            }
            else
            {
                picsize = string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.InsertImageDimensionsFormatScaled),
                                        MakeDimensions(currentWidth, currentHeight));
            }
            _fileSize.Text = picsize;
        }
Esempio n. 14
0
        /// <summary>
        /// Initializes and registers images with the editor.
        /// </summary>
        protected override void DoWork()
        {
            foreach (NewImageInfo newImage in this.newImages)
            {
                // Before starting on the next image, make sure we weren't cancelled.
                if (CancelRequested)
                {
                    AcknowledgeCancel();
                    return;
                }

                try
                {
                    // Register the image file as a BlogPostImageData so that the editor can manage the supporting files
                    ISupportingFile sourceFile = this.fileService.AddLinkedSupportingFileReference(newImage.ImageInfo.ImageSourceUri);
                    newImage.ImageData = new BlogPostImageData(new ImageFileData(sourceFile, newImage.ImageInfo.ImageSourceSize.Width, newImage.ImageInfo.ImageSourceSize.Height, ImageFileRelationship.Source));

                    // Create the shadow file if necessary.
                    if (GlobalEditorOptions.SupportsFeature(ContentEditorFeature.ShadowImageForDrafts))
                    {
                        newImage.ImageData.InitShadowFile(this.fileService);
                    }

                    // Create the initial inline image.
                    Stream inlineImageStream = new MemoryStream();
                    using (Bitmap sourceBitmap = new Bitmap(newImage.ImageInfo.ImageSourceUri.LocalPath))
                    {
                        string      extension;
                        ImageFormat imageFormat;
                        ImageHelper2.GetImageFormat(newImage.ImageInfo.ImageSourceUri.LocalPath, out extension, out imageFormat);

                        using (Bitmap resizedBitmap = ImageHelper2.CreateResizedBitmap(sourceBitmap, newImage.InitialSize.Width, newImage.InitialSize.Height, imageFormat))
                        {
                            // Resizing the bitmap is a time-consuming operation, so its possible we were cancelled during it.
                            if (CancelRequested)
                            {
                                AcknowledgeCancel();
                                return;
                            }

                            ImageHelper2.SaveImage(resizedBitmap, imageFormat, inlineImageStream);
                        }

                        inlineImageStream.Seek(0, SeekOrigin.Begin);
                    }

                    // Saving the bitmap is a time-consuming operation, so its possible we were cancelled during it.
                    if (CancelRequested)
                    {
                        AcknowledgeCancel();
                        return;
                    }

                    // Link up the initial inline image.
                    ISupportingFile imageFilePlaceholderHolder = this.fileService.CreateSupportingFile(Path.GetFileName(newImage.ImageInfo.ImageSourceUri.LocalPath), Guid.NewGuid().ToString(), inlineImageStream);
                    newImage.ImageData.InlineImageFile = new ImageFileData(imageFilePlaceholderHolder, newImage.InitialSize.Width, newImage.InitialSize.Height, ImageFileRelationship.Inline);
                }
                catch (Exception e)
                {
                    // Something failed for this image, flag this for removal
                    Debug.WriteLine("Image file could not be initialized: " + newImage.ImageInfo.ImageSourceUri.LocalPath + " " + e);
                    Trace.WriteLine("Could not initialize image: " + newImage.ImageInfo.ImageSourceUri.LocalPath);
                    Trace.WriteLine(e.ToString());
                    newImage.Remove = true;
                }
            }

            // We've successfully intialized all the images, but make sure we weren't cancelled at the last second.
            if (CancelRequested)
            {
                AcknowledgeCancel();
                return;
            }
        }