示例#1
0
        public static Drawing CreateDrawing(
            WordprocessingDocument package,
            Stream imageStream,
            ImagePartType imagePartType,
            int percentage, long maxWidthInEmus)
        {
            var imagePart = package.MainDocumentPart.AddImagePart(imagePartType);

#if NET35 || NET45
            var img = new BitmapImage();

            using (imageStream)
            {
                img.BeginInit();
                img.StreamSource = imageStream;
                img.EndInit();

                imageStream.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(imageStream);
                // imagePart will also dispose the stream.
            }

            var widthPx    = img.PixelWidth;
            var heightPx   = img.PixelHeight;
            var horzRezDpi = (int)img.DpiX;
            var vertRezDpi = (int)img.DpiY;
#else
            ImageInfoBase imageInfo = null;

            using (imageStream)
            {
                var type = GetImageInfoType(imagePartType);
                imageInfo = ImageInfo.GetInfo(type, imageStream);
                if (imageInfo == null)
                {
                    throw new ArgumentException("Unsupported image format.");
                }

                imageStream.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(imageStream);
                // imagePart will also dispose the stream.
            }

            var widthPx    = imageInfo.Width;
            var heightPx   = imageInfo.Height;
            var horzRezDpi = imageInfo.DpiH;
            var vertRezDpi = imageInfo.DpiV;
#endif
            const int emusPerInch = 914400;
            var       widthEmus   = (long)widthPx * emusPerInch / horzRezDpi;
            var       heightEmus  = (long)heightPx * emusPerInch / vertRezDpi;

            if (widthEmus > maxWidthInEmus)
            {
                var ratio = heightEmus * 1.0m / widthEmus;
                widthEmus  = maxWidthInEmus;
                heightEmus = (long)(widthEmus * ratio);
            }

            if (percentage != 100)
            {
                widthEmus  = widthEmus * percentage / 100;
                heightEmus = heightEmus * percentage / 100;
            }

            var drawing = GetDrawing(package.MainDocumentPart.GetIdOfPart(imagePart), widthEmus, heightEmus);
            return(drawing);
        }