<commit_before>﻿using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Drawing.Wordprocessing;
using DocumentFormat.OpenXml.Office.Drawing;
using DocumentFormat.OpenXml.Packaging;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Signum.Engine.Word
{
    public class WordImageReplacer
    {
        public static bool AvoidAdaptSize = false; //Jpeg compression creates different images in TeamCity

        public static void ReplaceImage(WordprocessingDocument doc, string title, Bitmap bitmap, string newImagePartId, bool adaptSize = false, ImagePartType imagePartType = ImagePartType.Png)
        {
            Blip blip = FindBlip(doc, title);

            if (adaptSize && !AvoidAdaptSize)
            {
                var part = doc.MainDocumentPart.GetPartById(blip.Embed);

                Bitmap oldBmp = (Bitmap)Bitmap.FromStream(part.GetStream());

                bitmap = ImageResizer.Resize(bitmap, oldBmp.Width, oldBmp.Height);
            }

            doc.MainDocumentPart.DeletePart(blip.Embed);

            ImagePart img = CreateImagePart(doc, bitmap, newImagePartId, imagePartType);

            blip.Embed = doc.MainDocumentPart.GetIdOfPart(img);
        }

        static ImagePart CreateImagePart(WordprocessingDocument doc, Bitmap bitmap, string id, ImagePartType imagePartType = ImagePartType.Png)
        {
            ImagePart img = doc.MainDocumentPart.AddImagePart(imagePartType, id);

            using (var ms = new MemoryStream())
            {
                bitmap.Save(ms, ToImageFormat(imagePartType));
                ms.Seek(0, SeekOrigin.Begin);
                img.FeedData(ms);
            }
            return img;
        }

        private static ImageFormat ToImageFormat(ImagePartType imagePartType)
        {
            switch (imagePartType)
            {
                case ImagePartType.Bmp: return ImageFormat.Bmp;
                case ImagePartType.Emf: return ImageFormat.Emf;
                case ImagePartType.Gif: return ImageFormat.Gif;
                case ImagePartType.Icon: return ImageFormat.Icon;
                case ImagePartType.Jpeg: return ImageFormat.Jpeg;
                case ImagePartType.Png: return ImageFormat.Png;
                case ImagePartType.Tiff: return ImageFormat.Tiff;
                case ImagePartType.Wmf: return ImageFormat.Wmf;
            }

            throw new InvalidOperationException("Unexpected {0}".FormatWith(imagePartType));
        }

        static Blip FindBlip(WordprocessingDocument doc, string alternativeTitle)
        {
            var drawing = doc.MainDocumentPart.Document.Descendants<Drawing>().SingleEx(r =>
            {
                var prop = r.Descendants<DocProperties>().SingleOrDefault();

                return prop != null && prop.Title == alternativeTitle;
            });

            return drawing.Descendants<Blip>().SingleEx();
        }
    }

    public static class ImageResizer
    {
        //http://stackoverflow.com/a/10445101/38670
        public static Bitmap Resize(Bitmap image, int width, int height)
        {
            var brush = new SolidBrush(Color.White);

            float scale = Math.Min(width / (float)image.Width, height / (float)image.Height);

            var bmp = new Bitmap((int)width, (int)height);
            var graph = Graphics.FromImage(bmp);

            // uncomment for higher quality output
            graph.InterpolationMode = InterpolationMode.High;<commit_msg>fix WordImageReplacer<commit_after>﻿using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Drawing.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Signum.Utilities;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Drawing.Drawing2D;

namespace Signum.Engine.Word
{
    public class WordImageReplacer
    {
        public static bool AvoidAdaptSize = false; //Jpeg compression creates different images in TeamCity

        /// <param name="title">Word Image -> Right Click -> Format Picture -> Alt Text -> Title </param>
        public static void ReplaceImage(WordprocessingDocument doc, string title, Bitmap bitmap, string newImagePartId, bool adaptSize = false, ImagePartType imagePartType = ImagePartType.Png)
        {
            Blip blip = FindBlip(doc, title);

            if (adaptSize && !AvoidAdaptSize)
            {
                var part = doc.MainDocumentPart.GetPartById(blip.Embed);

                Bitmap oldBmp = (Bitmap)Bitmap.FromStream(part.GetStream());

                bitmap = ImageResizer.Resize(bitmap, oldBmp.Width, oldBmp.Height);
            }

            doc.MainDocumentPart.DeletePart(blip.Embed);

            ImagePart img = CreateImagePart(doc, bitmap, newImagePartId, imagePartType);

            blip.Embed = doc.MainDocumentPart.GetIdOfPart(img);
        }

        static ImagePart CreateImagePart(WordprocessingDocument doc, Bitmap bitmap, string id, ImagePartType imagePartType = ImagePartType.Png)
        {
            ImagePart img = doc.MainDocumentPart.AddImagePart(imagePartType, id);

            using (var ms = new MemoryStream())
            {
                bitmap.Save(ms, ToImageFormat(imagePartType));
                ms.Seek(0, SeekOrigin.Begin);
                img.FeedData(ms);
            }
            return img;
        }

        private static ImageFormat ToImageFormat(ImagePartType imagePartType)
        {
            switch (imagePartType)
            {
                case ImagePartType.Bmp: return ImageFormat.Bmp;
                case ImagePartType.Emf: return ImageFormat.Emf;
                case ImagePartType.Gif: return ImageFormat.Gif;
                case ImagePartType.Icon: return ImageFormat.Icon;
                case ImagePartType.Jpeg: return ImageFormat.Jpeg;
                case ImagePartType.Png: return ImageFormat.Png;
                case ImagePartType.Tiff: return ImageFormat.Tiff;
                case ImagePartType.Wmf: return ImageFormat.Wmf;
            }

            throw new InvalidOperationException("Unexpected {0}".FormatWith(imagePartType));
        }

        static Blip FindBlip(WordprocessingDocument doc, string alternativeTitle)
        {
            var drawing = doc.MainDocumentPart.Document.Descendants().OfType<Drawing>().SingleEx(r =>
            {
                var prop = r.Descendants<DocProperties>().SingleOrDefault();

                return prop != null && prop.Title == alternativeTitle;
            });

            return drawing.Descendants<Blip>().SingleEx();
        }
    }

    public static class ImageResizer
    {
        //http://stackoverflow.com/a/10445101/38670
        internal static Bitmap Resize(Bitmap image, int width, int height)
        {
            var brush = new SolidBrush(System.Drawing.Color.White);

            float scale = Math.Min(width / (float)image.Width, height / (float)image.Height);

            var bmp = new Bitmap((int)width, (int)height);
            var graph = Graphics.FromImage(bmp);

            // uncomment for higher quality output
            graph.InterpolationMode = InterpolationMode.High;
{'fraction_non_alphanumeric': 0.08682107544358662, 'fraction_numerical': 0.00433428145740214, 'mean_word_length': 2.3426889995473066, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5038332', 'n_tokens_mistral': 2012, 'n_tokens_neox': 1910, 'n_words': 437}