Ejemplo n.º 1
0
        public static void Set(Uri uri, Style style, ImageFormat format)
        {
            Stream stream = new WebClient().OpenRead(uri.ToString());

            if (stream == null) return;

            Image img = Image.FromStream(stream);
            string tempPath = Path.Combine(Path.GetTempPath(), "img." + format.ToString());
            img.Save(tempPath, format);

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            if (style == Style.Stretched)
            {
                key.SetValue(@"WallpaperStyle", 2.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }

            if (style == Style.Centered)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 0.ToString());
            }

            if (style == Style.Tiled)
            {
                key.SetValue(@"WallpaperStyle", 1.ToString());
                key.SetValue(@"TileWallpaper", 1.ToString());
            }

            SystemParametersInfo(SpiSetdeskwallpaper,
                0,
                tempPath,
                SpifUpdateinifile | SpifSendwininichange);
        }
Ejemplo n.º 2
0
 public static Stream ToStream(this Image image, ImageFormat formaw)
 {
     var stream = new MemoryStream();
     image.Save(stream, formaw);
     stream.Position = 0;
     return stream;
 }
        /// <summary>
        /// 調整圖片壓縮解析度
        /// </summary>
        public static string ToBase64String_x1(Bitmap newBmp, ImageFormat iFormat)
        {
            MemoryStream ms = new MemoryStream();

            //save
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 30L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            newBmp.Save(ms, jgpEncoder, myEncoderParameters);

            //Bitmap new2Bmp = new Bitmap(ms);
            //new2Bmp.Save(@"c:\test002.jpg", iFormat);

            //newBmp.Save(ms, iFormat);
            ms.Seek(0, SeekOrigin.Begin);

            //建立一個byte
            //並且定義長度為MemoryStream的長度
            byte[] bytes = new byte[ms.Length];
            //MemoryStream讀取資料
            ms.Read(bytes, 0, (int)ms.Length);
            ms.Close();

            return Convert.ToBase64String(bytes);
        }
Ejemplo n.º 4
0
        public static ImageResult CreateImageFrom(byte[] bytes, ImageFormat format)
        {
            byte[] nonIndexedImageBytes;

            using (var memoryStream = new MemoryStream(bytes))
            using (var image = Image.FromStream(memoryStream))
            using (var temporaryBitmap = new Bitmap(image.Width, image.Height))
            {
                using (var graphics = Graphics.FromImage(temporaryBitmap))
                {
                    graphics.DrawImage(image, new Rectangle(0, 0, temporaryBitmap.Width, temporaryBitmap.Height),
                        0, 0, temporaryBitmap.Width, temporaryBitmap.Height, GraphicsUnit.Pixel);
                }

                ImagePropertyItems.Copy(image, temporaryBitmap);

                using (var saveStream = new MemoryStream())
                {
                    temporaryBitmap.Save(saveStream, format);
                    nonIndexedImageBytes = saveStream.ToArray();
                }
            }
            
            return new ImageResult(nonIndexedImageBytes, format);
        }
Ejemplo n.º 5
0
		internal void Save(Report rpt, System.IO.Stream stream, ImageFormat im)
		{
			if (_bm == null)
				Draw(rpt);
            _mf.Save(stream, im);
	//		_bm.Save(stream, im);
		}
Ejemplo n.º 6
0
 protected void ReturnImage(HttpContextBase context, string file, ImageFormat imageFormat, string contentType)
 {
     var buffer = GetImage(file, imageFormat);
     context.Response.ContentType = "image/png";
     context.Response.BinaryWrite(buffer);
     context.Response.Flush();
 }
Ejemplo n.º 7
0
 public void SaveImage(string filename, ImageFormat format)
 {
     if (bitmap != null)
     {
         bitmap.Save(filename, format);
     }
 }
Ejemplo n.º 8
0
        public WebImage(Stream imageStream) {
            if (imageStream.CanSeek) {
                imageStream.Seek(0, SeekOrigin.Begin);

                _content = new byte[imageStream.Length];
                using (BinaryReader reader = new BinaryReader(imageStream)) {
                    reader.Read(_content, 0, (int)imageStream.Length);
                }
            }
            else {
                List<byte[]> chunks = new List<byte[]>();
                int totalSize = 0;
                using (BinaryReader reader = new BinaryReader(imageStream)) {
                    // Pick some size for chunks that is still under limit
                    // that causes them to be placed on the large object heap.
                    int chunkSizeInBytes = 1024 * 50;
                    byte[] nextChunk = null;
                    do {
                        nextChunk = reader.ReadBytes(chunkSizeInBytes);
                        totalSize += nextChunk.Length;
                        chunks.Add(nextChunk);
                    }
                    while (nextChunk.Length == chunkSizeInBytes);
                }

                _content = new byte[totalSize];
                int startIndex = 0;
                foreach (var chunk in chunks) {
                    chunk.CopyTo(_content, startIndex);
                    startIndex += chunk.Length;
                }
            }
            _initialFormat = ValidateImageContent(_content, "imageStream");
            _currentFormat = _initialFormat;
        }
Ejemplo n.º 9
0
        public static MemoryStream CompressImage(ImageFormat format, Stream stream, Size size, bool isbig)
        {
            using (var image = Image.FromStream(stream))
            {
                Image bitmap = new Bitmap(size.Width, size.Height);
                Graphics g = Graphics.FromImage(bitmap);
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.Clear(Color.Transparent);

                //按指定面积缩小
                if (!isbig)
                {
                    g.DrawImage(image,
                                new Rectangle(0, 0, size.Width, size.Height),
                                ImageCutSize(image, size),
                                GraphicsUnit.Pixel);
                }
                //按等比例缩小
                else
                {
                    g.DrawImage(image,
                                new Rectangle(0, 0, size.Width, size.Height),
                                new Rectangle(0, 0, image.Width, image.Height),
                                GraphicsUnit.Pixel);
                }

                var compressedImageStream = new MemoryStream();
                bitmap.Save(compressedImageStream, format);
                g.Dispose();
                bitmap.Dispose();
                return compressedImageStream;
            }
        }
Ejemplo n.º 10
0
            /// <summary>
            /// 将Pdf转换成图片存放在指定的文件夹下面并且返回转换了多少张图片(插件:O2S.Components.PDFRender4NETd)
            /// (使用:调用此方法传递参数,最后一个参数为模糊度(参考传递30))
            /// </summary>
            /// <param name="pdfInputPath">源PDF路径</param>
            /// <param name="imageOutpPutPath">PDF转化成图片之后存放的路径</param>
            /// <param name="imageFormat">转换的图片格式</param>
            /// <param name="difinition">传递参数模糊度</param>
            /// <returns>返回转换了多少张图片信息</returns>
            public static int PdfConvertImageInfo(string pdfInputPath, string imageOutpPutPath, ImageFormat imageFormat,
                float difinition)
            {
                try
                {
                    //第一步:判断需要转换的PDF是否存在
                    if (!File.Exists(pdfInputPath))
                    {
                        throw new System.Exception("PDF的路径不存在");
                    }
                    //第二步:判断存放转换后图片的地址是否存在
                    if (!Directory.Exists(imageOutpPutPath))
                    {
                        throw new System.Exception("存放图片的路径不存在");
                    }
                    //第三步:进行转换(使用插件O2S.Components.PDFRender4NET)
                    PDFFile pdfFile = PDFFile.Open(pdfInputPath);
                    int pageCount = pdfFile.PageCount;
                    for (int i = 0; i < pageCount; i++)
                    {
                        Bitmap bitmap = pdfFile.GetPageImage(i, difinition);
                        bitmap.Save(Path.Combine(imageOutpPutPath, i + "." + imageFormat), imageFormat);
                        bitmap.Dispose();
                    }
                    pdfFile.Dispose();
                    //第四步:返回PDF转换了多少张图片的个数
                    return pageCount;
                }
                catch (System.Exception exception)
                {

                    throw new System.Exception("PDF转换图片出现错误了,错误原因:" + exception.Message);
                }
            }
        /// <summary>
        /// 将Word文档转换为图片的方法(该方法基于第三方DLL),你可以像这样调用该方法:
        /// ConvertPDF2Image("F:\\PdfFile.doc", "F:\\", "ImageFile", 1, 20, ImageFormat.Png, 256);
        /// </summary>
        /// <param name="pdfInputPath">Word文件路径</param>
        /// <param name="imageOutputPath">图片输出路径,如果为空,默认值为Word所在路径</param>
        /// <param name="imageName">图片的名字,不需要带扩展名,如果为空,默认值为Word的名称</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
        /// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
        /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        public static void ConvertWordToImage(string wordInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, float resolution)
        {
            try
            {
                // open word file
                Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);

                // validate parameter
                if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密!"); }
                if (imageOutputPath.Trim().Length == 0) { imageOutputPath = Path.GetDirectoryName(wordInputPath); }
                if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); }
                if (imageName.Trim().Length == 0) { imageName = Path.GetFileNameWithoutExtension(wordInputPath); }
                if (startPageNum <= 0) { startPageNum = 1; }
                if (endPageNum > doc.PageCount || endPageNum <= 0) { endPageNum = doc.PageCount; }
                if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; }
                if (imageFormat == null) { imageFormat = ImageFormat.Png; }
                if (resolution <= 0) { resolution = 128; }

                ImageSaveOptions imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat));
                imageSaveOptions.Resolution = resolution;

                // start to convert each page
                for (int i = startPageNum; i <= endPageNum; i++)
                {
                    imageSaveOptions.PageIndex = i - 1;
                    doc.Save(Path.Combine(imageOutputPath, imageName) + "_" + i.ToString() + "." + imageFormat.ToString(), imageSaveOptions);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 public static Bitmap GetThumbnail(int width, int height, string filter, string caption, ImageFormat format, Image b)
 {
     Bitmap source = new Bitmap(b);
     source = new Bitmap(source.GetThumbnailImage(width, height, null, IntPtr.Zero));
     if (format == ImageFormat.Gif)
     {
         source = new OctreeQuantizer(0xff, 8).Quantize(source);
     }
     if ((filter.Length > 0) && filter.ToUpper().StartsWith("SHARPEN"))
     {
         string str = filter.Remove(0, 7).Trim();
         int nWeight = (str.Length > 0) ? Convert.ToInt32(str) : 11;
         BitmapFilter.Sharpen(source, nWeight);
     }
     if (caption.Length <= 0)
     {
         return source;
     }
     using (Graphics graphics = Graphics.FromImage(source))
     {
         StringFormat format2 = new StringFormat();
         format2.Alignment = StringAlignment.Center;
         format2.LineAlignment = StringAlignment.Center;
         using (Font font = new Font("Arial", 12f))
         {
             graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; 
             graphics.FillRectangle(new SolidBrush(Color.FromArgb(150, 0, 0, 0)), 0, source.Height - 20, source.Width, 20);
             graphics.DrawString(caption, font, Brushes.White, 0f, (float)(source.Height - 20));
             return source;
         }
     }
 }
Ejemplo n.º 13
0
        /// <summary>
        /// To the bitmap source.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        /// <param name="format">The format.</param>
        /// <param name="creationOptions">The creation options.</param>
        /// <param name="cacheOptions">The cache options.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">bitmap</exception>
        public static BitmapSource ToBitmapSource(this Bitmap bitmap, ImageFormat format, BitmapCreateOptions creationOptions = BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption cacheOptions = BitmapCacheOption.OnLoad)
        {
            if (bitmap == null)
                throw new ArgumentNullException("bitmap");

            using (MemoryStream memoryStream = new MemoryStream())
            {
                try
                {
                    // You need to specify the image format to fill the stream.
                    // I'm assuming it is PNG
                    bitmap.Save(memoryStream, format);
                    memoryStream.Seek(0, SeekOrigin.Begin);

                    BitmapDecoder bitmapDecoder = BitmapDecoder.Create(
                        memoryStream,
                        creationOptions,
                        cacheOptions);

                    // This will disconnect the stream from the image completely...
                    WriteableBitmap writable =
            new WriteableBitmap(bitmapDecoder.Frames.Single());
                    writable.Freeze();

                    return writable;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
Ejemplo n.º 14
0
         public Image ScanImage(ImageFormat outputFormat, string fileName)
         {
              if (outputFormat == null)
                   throw new ArgumentNullException("outputFormat");

              FileIOPermission filePerm = new FileIOPermission(FileIOPermissionAccess.AllAccess, fileName);
              filePerm.Demand();

              ImageFile imageObject = null;

              try
              {
                   if (WiaManager == null)
                        WiaManager = new CommonDialogClass();

                   imageObject =
                        WiaManager.ShowAcquireImage(WiaDeviceType.ScannerDeviceType,
                             WiaImageIntent.GrayscaleIntent, WiaImageBias.MaximizeQuality, 
                             outputFormat.Guid.ToString("B"), false, true, true);

                   imageObject.SaveFile(fileName);
                   return Image.FromFile(fileName);
              }
              catch (COMException ex)
              {
                   string message = "Error scanning image";
                   throw new WiaOperationException(message, ex);
              }
              finally
              {
                   if (imageObject != null)
                        Marshal.ReleaseComObject(imageObject);
              }
         }
Ejemplo n.º 15
0
 private void SaveImageAs(int bitmap, string fileName, ImageFormat imageFormat)
 {
     Bitmap image = new Bitmap(Image.FromHbitmap(new IntPtr(bitmap)),
         Image.FromHbitmap(new IntPtr(bitmap)).Width,
         Image.FromHbitmap(new IntPtr(bitmap)).Height);
     image.Save(fileName, imageFormat);
 }
        private ImageCodecInfo GetEncoder(ImageFormat format)
        {

            var codecs = ImageCodecInfo.GetImageDecoders();

            return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid);
        }
Ejemplo n.º 17
0
        byte[] GetResizedImage(Stream originalStream, ImageFormat imageFormat, int width, int height)
        {
            Bitmap imgIn = new Bitmap(originalStream);
            double y = imgIn.Height;
            double x = imgIn.Width;

            double factor = 1;
            if (width > 0)
            {
                factor = width / x;
            }
            else if (height > 0)
            {
                factor = height / y;
            }
            System.IO.MemoryStream outStream = new System.IO.MemoryStream();
            Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));

            // Set DPI of image (xDpi, yDpi)
            imgOut.SetResolution(72, 72);

            Graphics g = Graphics.FromImage(imgOut);
            g.Clear(Color.White);
            g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)),
              new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

            imgOut.Save(outStream, imageFormat);
            return outStream.ToArray();
        }
Ejemplo n.º 18
0
		/// <summary>
		/// Saves the specified render target as an image with the specified format.
		/// </summary>
		/// <param name="renderTarget">The render target to save.</param>
		/// <param name="stream">The stream to which to save the render target data.</param>
		/// <param name="format">The format with which to save the image.</param>
		private void Save(RenderTarget2D renderTarget, Stream stream, ImageFormat format)
		{
			var data = new Color[renderTarget.Width * renderTarget.Height];
			renderTarget.GetData(data);

			Save(data, renderTarget.Width, renderTarget.Height, stream, format);
		}
Ejemplo n.º 19
0
        public static string imageFormatToMimeType(ImageFormat imageFormat)
        {

            if (imageFormat == ImageFormat.Tiff)
            {
                return ("image/tiff");
            }
            else if (imageFormat == ImageFormat.Gif)
            {
                return ("image/gif");
            }
            else if (imageFormat == ImageFormat.Png)
            {
                return ("image/png");
            }
            else if (imageFormat == ImageFormat.Jpeg)
            {
                return ("image/jpeg");
            }
            else if (imageFormat == ImageFormat.Bmp)
            {
                return ("image/bmp");
            }
            else
            {
                return (null);
            }

        }
Ejemplo n.º 20
0
        // Create a bitmap file of the mapDisplay supplied at construction.
        public void CreateBitmap(string fileName, RectangleF rect, ImageFormat imageFormat, float dpi)
        {
            float bitmapWidth, bitmapHeight; // size of the bitmap in pixels.
            int pixelWidth, pixelHeight; // bitmapWidth/Height, rounded up to integer.

            bitmapWidth = (rect.Width / 25.4F) * dpi;
            bitmapHeight = (rect.Height / 25.4F) * dpi;
            pixelWidth = (int)Math.Ceiling(bitmapWidth);
            pixelHeight = (int) Math.Ceiling(bitmapHeight);

            Bitmap bitmap = new Bitmap(pixelWidth, pixelHeight, PixelFormat.Format24bppRgb);
            bitmap.SetResolution(dpi, dpi);

            // Set the transform
            Matrix transform = Geometry.CreateInvertedRectangleTransform(rect, new RectangleF(0, 0, bitmapWidth, bitmapHeight));

            // And draw.
            mapDisplay.Draw(bitmap, transform);

            // JPEG and GIF have special code paths because the default Save method isn't
            // really good enough.
            if (imageFormat == ImageFormat.Jpeg)
                BitmapUtil.SaveJpeg(bitmap, fileName, 80);
            else if (imageFormat == ImageFormat.Gif)
                BitmapUtil.SaveGif(bitmap, fileName);
            else
                bitmap.Save(fileName, imageFormat);

            bitmap.Dispose();
        }
Ejemplo n.º 21
0
 private void GenerateImage(
     HttpResponse response,
     string textToInsert,
     int width,
     int height,
     Color backgroundColor,
     FontFamily fontFamily,
     float emSize,
     Brush brush,
     float x,
     float y,
     string contentType,
     ImageFormat imageFormat)
 {
     using (Bitmap bitmap = new Bitmap(width, height))
     {
         using (Graphics graphics = Graphics.FromImage(bitmap))
         {
             graphics.Clear(backgroundColor);
             graphics.DrawString(textToInsert, new Font(fontFamily, emSize), brush, x, y);
             response.ContentType = contentType;
             bitmap.Save(response.OutputStream, imageFormat);
         }
     }
 }
Ejemplo n.º 22
0
        public static Stream Normalize(Image input, int ow, int oh, bool crop, ImageFormat outputFormat)
        {
            Contract.Requires(input != null, "input");
            Contract.Requires(outputFormat != null, "outputFormat");
            Contract.Ensures(Contract.Result<Stream>() != null);
            // Create output canvas

            // Store CURRENT sizes (solution cannot be bigger than these)
            double iw = input.Width;
            double ih = input.Height;

            // Calculate resize ratio
            double r = 1;
            if (crop) { // Fill
                if (ow / iw > oh / ih) { // Width is bigger
                    r = ow / iw;
                } else { // Height is bigger
                    r = oh / ih;
                }
            } else { // Max
                if (ow / iw > oh / ih) { // Width is bigger
                    r = oh / ih;
                } else { // Height is bigger
                    r = ow / iw;
                }
            }

            // Calculate the new image size (if cropped, this will be bigger than the canvas)
            int w = Convert.ToInt32(iw * r);
            int h = Convert.ToInt32(ih * r);

            // Calculate the draw position (centering when cropping)
            int x = w < ow ? 0 : (ow - w) / 2;
            int y = h < oh ? 0 : (oh - h) / 2;

            // If the image is smaller than the expected canvas, shrink the canvas to fit
            if (w < ow) {
                ow = w;
            }
            if (h < oh) {
                oh = h;
            }

            // Resize and crop image based on these paramaters
            using (var output = new Bitmap(ow, oh)) {
                using (var graphic = Graphics.FromImage(output)) {
                    graphic.CompositingQuality = CompositingQuality.HighQuality;
                    graphic.SmoothingMode = SmoothingMode.HighQuality;
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.DrawImage(input, new Rectangle(x, y, w, h));
                }

                // Convert canvas to stream
                var resizedStream = new MemoryStream();
                output.Save(resizedStream, outputFormat);
                resizedStream.Position = 0;

                return resizedStream;
            }
        }
Ejemplo n.º 23
0
 public static void Save(Byte[] imageBytes, string fullImagePath, ImageFormat format)
 {
     using (Stream ImageStream = new MemoryStream(imageBytes))
     {
         Save(ImageStream, fullImagePath, fullImagePath, format);
     }
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Constructor por defecto.
 /// </summary>
 public frmFondo(string ruta, ImageFormat formato, bool original, int width, int height)
 {
     InitializeComponent();
     this.original = original;
     this.width = width;
     this.height = height;
     //Establecemos el ancho de la forma a la resolución actual de pantalla
     this.Bounds = Screen.GetBounds(this.ClientRectangle);
     //Inicializamos las variables
     origen = new Point(0, 0);
     destino = new Point(0, 0);
     actual = new Point(0, 0);
     //De momento nuestro gráfico es nulo
     areaSeleccionada = this.CreateGraphics();
     //El estilo de línea del lápiz serán puntos
     lapizActual.DashStyle = DashStyle.Solid;
     //Establecemos falsa la variable que nos indica si el boton presionado fue el boton izquierdo
     BotonIzq = false;
     //Delegados para manejar los eventos del mouse y poder dibujar el rectangulo del área que deseamos copiar
     this.MouseDown += new MouseEventHandler(mouse_Click);
     this.MouseUp += new MouseEventHandler(mouse_Up);
     this.MouseMove += new MouseEventHandler(mouse_Move);
     this.ruta = ruta;
     this.formato = formato;
 }
        public static ImageFormatTypes GetImageFormat(ImageFormat type)
        {
            if (type == ImageFormat.Bmp)
                return ImageFormatTypes.imgBMP;
            else
                if (type == ImageFormat.Emf)
                    return ImageFormatTypes.imgEMF;
                else
                    if (type == ImageFormat.Exif)
                        return ImageFormatTypes.imgEXIF;
                    else
                        if (type == ImageFormat.Gif)
                            return ImageFormatTypes.imgGIF;
                        else
                            if (type == ImageFormat.Icon)
                                return ImageFormatTypes.imgICON;
                            else
                                if (type == ImageFormat.Jpeg)
                                    return ImageFormatTypes.imgJPEG;
                                else
                                    if (type == ImageFormat.Png)
                                        return ImageFormatTypes.imgPNG;
                                    else
                                        if (type == ImageFormat.Tiff)
                                            return ImageFormatTypes.imgTIFF;
                                        else
                                            if (type == ImageFormat.Wmf)
                                                return ImageFormatTypes.imgWMF;

            return ImageFormatTypes.imgNone;
        }
Ejemplo n.º 26
0
        public static Stream ResizeImage(Image image, ImageFormat format, int width, int height, bool preserveAspectRatio = true)
        {
            ImageHelper.ImageRotation(image);
            int newWidth;
            int newHeight;
            if (preserveAspectRatio)
            {
                int originalWidth = image.Width;
                int originalHeight = image.Height;
                float percentWidth = (float)width / (float)originalWidth;
                float percentHeight = (float)height / (float)originalHeight;
                float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
                newWidth = (int)(originalWidth * percent);
                newHeight = (int)(originalHeight * percent);
            }
            else
            {
                newWidth = width;
                newHeight = height;
            }
            Image newImage = new Bitmap(newWidth, newHeight);

            using (Graphics graphicsHandle = Graphics.FromImage(newImage))
            {
                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            //return newImage;
            var stream = new MemoryStream();
            newImage.Save(stream, format);
            stream.Position = 0;
            return stream;
        }
 WebApiPictureContext GetPictureWebApi(string filePath, ImageFormat format, double width, double height, double positionX, double positionY)
 {
     WebApiPictureContext retVal = new WebApiPictureContext();
     retVal.Base64String = GetBaseStringFromImage(new Bitmap(filePath), format);
     retVal.Location = new WebApiPictureData { BoundsHeight = height, BoundsWidth = width, BoundsLocationX = positionX, BoundsLocationY = positionY};
     return retVal;
 }
Ejemplo n.º 28
0
 public static Stream Save(this Bitmap bitmap, ImageFormat format)
 {
     var stream = new MemoryStream();
     bitmap.Save(stream, format);
     stream.Position = 0;
     return stream;
 }
Ejemplo n.º 29
0
		/// <summary>
		/// Saves the specified surface as an image with the specified format.
		/// </summary>
		/// <param name="surface">The surface to save.</param>
		/// <param name="stream">The stream to which to save the surface data.</param>
		/// <param name="format">The format with which to save the image.</param>
		private void Save(Surface2D surface, Stream stream, ImageFormat format)
		{
			var data = new Color[surface.Width * surface.Height];
			surface.GetData(data);

			Save(data, surface.Width, surface.Height, stream, format);
		}
Ejemplo n.º 30
0
 public static void Save(Stream imageStream, string fullImagePath, ImageFormat format)
 {
     using (Bitmap ImageBitmap = new Bitmap(imageStream))
     {
         Save(ImageBitmap, fullImagePath, format);
     }
 }
Ejemplo n.º 31
0
        public static byte[] ToByteArray(this Drawing.Image image, Drawing.Imaging.ImageFormat format)
        {
            using (var stream = new MemoryStream())
            {
                image.Save(stream, format);

                stream.Position = 0;

                return(stream.ToArray());
            }
        }
Ejemplo n.º 32
0
 private byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert,
                                        System.Drawing.Imaging.ImageFormat formatOfImage)
 {
     byte[] Ret;
     try
     {
         using (MemoryStream ms = new MemoryStream())
         {
             imageToConvert.Save(ms, formatOfImage);
             Ret = ms.ToArray();
         }
     }
     catch (Exception) { throw; }
     return(Ret);
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Saves the image.
 /// </summary>
 /// <param name="outputFormat">The output format.</param>
 /// <param name="image">The image.</param>
 /// <param name="toStream">To stream.</param>
 /// <param name="quality">The quality.</param>
 public static void Save(this Image image, System.Drawing.Imaging.ImageFormat outputFormat, Stream toStream, int quality)
 {
     // Use special save methods for jpeg and png that will result in a much higher quality image
     // All other formats use the generic Image.Save
     if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(outputFormat))
     {
         SaveAsJpeg(image, toStream, quality);
     }
     else if (System.Drawing.Imaging.ImageFormat.Png.Equals(outputFormat))
     {
         image.Save(toStream, System.Drawing.Imaging.ImageFormat.Png);
     }
     else
     {
         image.Save(toStream, outputFormat);
     }
 }
Ejemplo n.º 34
0
        /// <summary>
        /// 生成略缩图
        /// </summary>
        /// <param name="fileName">源文件路径</param>
        /// <param name="newFile">新文件路径</param>
        /// <param name="maxWidth">生成新文件的宽度,高度自动算</param>
        public static void SmallImageGenerated(string fileName, string newFile, int maxWidth)
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(fileName);
            System.Drawing.Imaging.ImageFormat
                thisFormat = img.RawFormat;
            int maxHeight  = img.Height * maxWidth / img.Width;
            //int maxHeight = 200;
            Size     newSize = new Size(maxWidth, maxHeight);
            Bitmap   outBmp  = new Bitmap(newSize.Width, newSize.Height);
            Graphics g       = Graphics.FromImage(outBmp);  // 设置画布的描绘质量

            g.DrawImage(img, new System.Drawing.Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
            g.Dispose();
            // 以下代码为保存图片时,设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();

            long[] quality = new long[1];
            quality[0] = 100;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            encoderParams.Param[0] = encoderParam;
            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   jpegICI  = null;

            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];
                    //设置JPEG编码
                    break;
                }
            }
            if (jpegICI != null)
            {
                outBmp.Save(newFile, jpegICI, encoderParams);
            }
            else
            {
                outBmp.Save(newFile,
                            thisFormat);
            }
            img.Dispose();
            outBmp.Dispose();
        }
Ejemplo n.º 35
0
        /// <summary>
        /// scale image to fit current page
        /// </summary>
        /// <param name="b">source image</param>
        /// <param name="destHeight">page height</param>
        /// <param name="destWidth">page width</param>
        /// <returns></returns>
        public Bitmap ScaleFitPage(Bitmap b, int destHeight, int destWidth)
        {
            System.Drawing.Image imgSource = b;
            System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;
            int sW = 0, sH = 0;
            // equal scale
            int sWidth = imgSource.Width;
            int sHeight = imgSource.Height;

            if (sHeight > destHeight || sWidth > destWidth)
            {
                if ((sWidth * destHeight) > (sHeight * destWidth))
                {
                    sW = destWidth;
                    sH = (destWidth * sHeight) / sWidth;
                }
                else
                {
                    sH = destHeight;
                    sW = (sWidth * destHeight) / sHeight;
                }
            }
            else
            {
                sW = sWidth;
                sH = sHeight;
            }
            Bitmap   outBmp = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(outBmp);

            g.Clear(Color.Transparent);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            EncoderParameters encoderParams = new EncoderParameters();

            long[] quality = new long[1];
            quality[0] = 100;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            encoderParams.Param[0] = encoderParam;
            imgSource.Dispose();
            return(outBmp);
        }
Ejemplo n.º 36
0
        private static Stream RotateImage(string rotateTypes, string physicalPath, System.Drawing.Imaging.ImageFormat imageFormat)
        {
            Stream imageStream = new MemoryStream();

            if (!string.IsNullOrEmpty(rotateTypes))
            {
                using (Image image = Image.FromFile(physicalPath))
                {
                    var rotates = rotateTypes.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var rotateType in rotates)
                    {
                        switch (rotateType)
                        {
                        case "1":     //逆时针旋转90
                            image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            break;

                        case "2":    //顺时针旋转90
                            image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            break;

                        case "3":    //垂直翻转
                            image.RotateFlip(RotateFlipType.Rotate180FlipX);
                            break;

                        case "4":    //水平翻转
                            image.RotateFlip(RotateFlipType.Rotate180FlipY);
                            break;

                        default:
                            break;
                        }
                    }
                    image.Save(imageStream, imageFormat);
                }
            }
            else
            {
                using (var fs = new FileStream(physicalPath, FileMode.Open, FileAccess.Read))
                {
                    fs.CopyTo(imageStream);
                }
            }
            imageStream.Position = 0;
            return(imageStream);
        }
Ejemplo n.º 37
0
        private void EncodeBitmap(Image image, Stream stream, IImageEncoderOptions encoderOptions)
        {
            using (EncoderParameters encoderParameters = new EncoderParameters(1))
                using (EncoderParameter qualityParameter = new EncoderParameter(Encoder.Quality, encoderOptions.Quality)) {
                    encoderParameters.Param[0] = qualityParameter;

                    System.Drawing.Imaging.ImageFormat format = imageFormat is null ? image.RawFormat : GetImageFormatFromFileExtension(imageFormat.Extensions.FirstOrDefault());
                    ImageCodecInfo encoder = GetEncoderFromImageFormat(format);

                    if (encoder is null)
                    {
                        encoder = GetEncoderFromImageFormat(System.Drawing.Imaging.ImageFormat.Png);
                    }

                    image.Save(stream, encoder, encoderParameters);
                }
        }
Ejemplo n.º 38
0
 public static byte[] ImageToByteArray(System.Drawing.Image imageOrg, System.Drawing.Imaging.ImageFormat saveFormat,
                                       bool isDeleteOrgin = false)
 {
     if (null == imageOrg)
     {
         return(null);
     }
     using (var ms = new MemoryStream())
     {
         imageOrg.Save(ms, saveFormat);
         if (isDeleteOrgin)
         {
             DestroyDisposableObj(imageOrg);
         }
         return(ms.ToArray());
     }
 }
        private void Save_button_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveImageDialog = new SaveFileDialog();

            saveImageDialog.Title  = "图片保存";
            saveImageDialog.Filter = @"jpeg|*.jpg|bmp|*.bmp";
            if (saveImageDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = saveImageDialog.FileName.ToString();
                if (fileName != "" && fileName != null)
                {
                    string fileExtName = fileName.Substring(fileName.LastIndexOf(".") + 1).ToString();
                    System.Drawing.Imaging.ImageFormat imgformat = null;


                    if (fileExtName != "")
                    {
                        switch (fileExtName)
                        {
                        case "jpg":
                            imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                            break;

                        case "bmp":
                            imgformat = System.Drawing.Imaging.ImageFormat.Bmp;
                            break;

                        default:
                            imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                            break;
                        }


                        try
                        {
                            Bitmap bit = new Bitmap(data_pictureBox.Image);
                            MessageBox.Show(fileName);
                            data_pictureBox.Image.Save(fileName, imgformat);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
Ejemplo n.º 40
0
        private ImageCodecInfo GetEncoder(GDIIMAGEFORMAT format)
        {
            if (_CodecsCache == null)
            {
                _CodecsCache = ImageCodecInfo.GetImageEncoders();
            }

            foreach (var codec in _CodecsCache)
            {
                if (codec.FormatID == format.Guid)
                {
                    return(codec);
                }
            }

            return(null);
        }
Ejemplo n.º 41
0
        private static Stream RotateImage(string rotateTypes, Stream inputStream, System.Drawing.Imaging.ImageFormat imageFormat)
        {
            Stream imageStream = new MemoryStream();

            if (!string.IsNullOrEmpty(rotateTypes))
            {
                using (Image image = Image.FromStream(inputStream))
                {
                    var rotates = rotateTypes.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var rotateType in rotates)
                    {
                        switch (rotateType)
                        {
                        case "1":     //逆时针旋转90
                            image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            break;

                        case "2":    //顺时针旋转90
                            image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            break;

                        case "3":    //垂直翻转
                            image.RotateFlip(RotateFlipType.Rotate180FlipX);
                            break;

                        case "4":    //水平翻转
                            image.RotateFlip(RotateFlipType.Rotate180FlipY);
                            break;

                        default:
                            break;
                        }
                    }
                    image.Save(imageStream, imageFormat);
                    image.Dispose();
                }
            }
            else
            {
                inputStream.Position = 0;
                inputStream.CopyTo(imageStream);
            }
            imageStream.Position = 0;
            return(imageStream);
        }
Ejemplo n.º 42
0
 public static byte[] GetBytes(Image Image, System.Drawing.Imaging.ImageFormat ImageFormat)
 {
     try
     {
         if (Image != null)
         {
             MemoryStream MS = new MemoryStream();
             Image.Save(MS, ImageFormat);
             MS.Position = 0;
             return(MS.ToArray());
         }
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
     return(null);
 }
Ejemplo n.º 43
0
 public bool SaveImage(Stream ms, System.Drawing.Imaging.ImageFormat format)
 {
     if (_image == null)
     {
         return(false);
     }
     try
     {
         try
         {
             if (Display.MakeTransparent &&
                 format != ImageFormat.Jpeg &&
                 format != ImageFormat.Gif)
             {
                 _image.MakeTransparent(Display.TransparentColor);
             }
         }
         catch (Exception ex)
         {
             if (this.MapServer != null)
             {
                 this.MapServer.Log(
                     "RenderRasterLayerThread", loggingMethod.error,
                     "Image.MakeTransparent\n'\nFormat=" + format.ToString() + "\n" +
                     ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
             }
         }
         _image.Save(ms, format);
         _image.Dispose();
         _image = null;
         return(true);
     }
     catch (Exception ex)
     {
         if (this.MapServer != null)
         {
             this.MapServer.Log(
                 "RenderRasterLayerThread", loggingMethod.error,
                 "Image.Save\n'\nFormat=" + format.ToString() + "\n" +
                 ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
         }
         return(false);
     }
 }
Ejemplo n.º 44
0
        /// <summary>
        /// 压缩指定尺寸,如果写的和图片大家一样表示大小不变,只是把图片压缩下一些
        /// </summary>
        /// <param name="oldfile">原文件</param>
        /// <param name="newfile">新文件</param>
        /// <param name="width">长</param>
        /// <param name="height">高</param>
        public bool Compress(string oldfile, string newfile, int width, int height)
        {
            try
            {
                System.Drawing.Image img = System.Drawing.Image.FromFile(oldfile);
                System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;
                Size     newSize = new Size(width, height);
                Bitmap   outBmp  = new Bitmap(newSize.Width, newSize.Height);
                Graphics g       = Graphics.FromImage(outBmp);
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.SmoothingMode      = SmoothingMode.HighQuality;
                g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                g.Dispose();
                EncoderParameters encoderParams = new EncoderParameters();
                long[]            quality       = new long[1];
                quality[0] = 100;
                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICI  = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[x]; //设置JPEG编码
                        break;
                    }
                }

                img.Dispose();
                if (jpegICI != null)
                {
                    outBmp.Save(newfile, System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                outBmp.Dispose();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 45
0
        public static System.Drawing.Bitmap GetThumbnail(System.Drawing.Bitmap b, int destHeight, int destWidth)
        {
            System.Drawing.Imaging.ImageFormat rawFormat = b.RawFormat;
            int width  = b.Width;
            int height = b.Height;
            int num;
            int num2;

            if (height > destHeight || width > destWidth)
            {
                if (width * destHeight < height * destWidth)
                {
                    num  = destWidth;
                    num2 = destWidth * height / width;
                }
                else
                {
                    num2 = destHeight;
                    num  = width * destHeight / height;
                }
            }
            else
            {
                num  = destWidth;
                num2 = destHeight;
            }
            System.Drawing.Bitmap   bitmap   = new System.Drawing.Bitmap(destWidth, destHeight);
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
            graphics.Clear(System.Drawing.Color.Transparent);
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphics.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(b, new System.Drawing.Rectangle((destWidth - num) / 2, (destHeight - num2) / 2, num, num2), 0, 0, b.Width, b.Height, System.Drawing.GraphicsUnit.Pixel);
            graphics.Dispose();
            System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters();
            long[] value = new long[]
            {
                100L
            };
            System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, value);
            encoderParameters.Param[0] = encoderParameter;
            b.Dispose();
            return(bitmap);
        }
Ejemplo n.º 46
0
        public static Image ZoomImage(Image sourceImage, int targetWidth, int targetHeight)
        {
            try
            {
                int width;
                int height;

                System.Drawing.Imaging.ImageFormat format = sourceImage.RawFormat;
                Bitmap   targetPicture = new Bitmap(targetWidth, targetHeight);
                Graphics g             = Graphics.FromImage(targetPicture);
                g.Clear(Color.White);
                if (sourceImage.Width > targetWidth && sourceImage.Height <= targetHeight)
                {
                    width  = targetWidth;
                    height = (width * sourceImage.Height) / sourceImage.Width;
                }
                else if (sourceImage.Width <= targetWidth && sourceImage.Height > targetHeight)
                {
                    height = targetHeight;
                    width  = (height * sourceImage.Width) / sourceImage.Height;
                }
                else if (sourceImage.Width <= targetWidth && sourceImage.Height <= targetHeight)
                {
                    width  = sourceImage.Width;
                    height = sourceImage.Height;
                }
                else
                {
                    width  = targetWidth;
                    height = (width * sourceImage.Height) / sourceImage.Width;
                    if (height > targetHeight)
                    {
                        height = targetHeight;
                        width  = (height * sourceImage.Width) / sourceImage.Height;
                    }
                }
                g.DrawImage(sourceImage, (targetWidth - width) / 2, (targetHeight - height) / 2, width, height);
                sourceImage.Dispose();
                return(targetPicture);
            }
            catch (Exception ee)
            { throw ee; }
        }
Ejemplo n.º 47
0
    public static byte[] ResizeImage(Stream imageStream, System.Drawing.Imaging.ImageFormat format)
    {
        System.Drawing.Image orignImage = System.Drawing.Image.FromStream(imageStream);
        byte[] result;
        System.Drawing.Image resized;
        if (orignImage.Height > GlobalSetting.MaxImageHeight || orignImage.Width > GlobalSetting.MaxImageWidth)
        {
            resized = ResizeImage(orignImage, new System.Drawing.Size(GlobalSetting.MaxImageWidth, GlobalSetting.MaxImageHeight), true);
        }
        else
        {
            resized = orignImage;
        }
        MemoryStream memStream = new MemoryStream();

        resized.Save(memStream, format);
        result = memStream.ToArray();
        return(result);
    }
Ejemplo n.º 48
0
Archivo: KLoad.cs Proyecto: yijin/h5
        public static bool LoadImg(string saveimgname, string imgurl)
        {
            WebRequest      wreq  = WebRequest.Create(imgurl);
            HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
            Stream          s     = wresp.GetResponseStream();

            System.Drawing.Image img;
            img = System.Drawing.Image.FromStream(s);
            try
            {
                if (img != null)
                {
                    FileInfo f = new FileInfo(saveimgname);
                    if (!Directory.Exists(f.DirectoryName))
                    {
                        Directory.CreateDirectory(f.DirectoryName);
                    }
                    System.Drawing.Imaging.ImageFormat iformat = KImage.GetImageType(imgurl);

                    if (iformat != null)
                    {
                        img.Save(saveimgname, iformat);
                    }
                    else
                    {
                        img.Save(saveimgname);
                    }
                }
                if (s != null)
                {
                    s.Close();
                }
                return(true);
            }
            catch (Exception e)
            {
                if (s != null)
                {
                    s.Close();
                }
                return(false);
            }
        }
Ejemplo n.º 49
0
        //Función auxiliar para obtener la extensión del fichero a guardar según el formato de imagen.
        private string getExtension(System.Drawing.Imaging.ImageFormat format)
        {
            string ext = "";

            if (format == ImageFormat.Png)
            {
                ext = "png";
            }
            else if (format == ImageFormat.Jpeg)
            {
                ext = "jpg";
            }
            else if (format == ImageFormat.Wmf)
            {
                ext = "wmf";
            }

            return(ext);
        }
Ejemplo n.º 50
0
        private void _WriteBitmap(Stream stream, GDIIMAGEFORMAT fmt, System.Drawing.Bitmap tmp)
        {
            var customOptions = false;

            customOptions |= _Quality.HasValue;

            if (!customOptions)
            {
                tmp.Save(stream, fmt);
                return;
            }

            var encoder = GetEncoder(fmt);

            using (var ppp = new EncoderParameters(1))
            {
                ppp.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)_Quality.Value);
                tmp.Save(stream, encoder, ppp);
            }
        }
Ejemplo n.º 51
0
        public static string ConvertImageToText(Image image, System.Drawing.Imaging.ImageFormat format)
        {
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    // Convert Image to byte[]
            //    image.Save(ms, format);
            //    byte[] imageBytes = ms.ToArray();

            //    // Convert byte[] to Base64 String
            //    string base64String = Convert.ToBase64String(imageBytes);
            //    return base64String;
            //}

            using (MemoryStream memoryStream = new MemoryStream())
            {
                image.Save(memoryStream, ImageFormat.Png);
                byte[] bitmapBytes = memoryStream.GetBuffer();
                return(Convert.ToBase64String(bitmapBytes));
            }
        }
Ejemplo n.º 52
0
            /// <summary>
            /// Guarda una imagen a fichero con un formato determinado indicado como parámetro.
            /// </summary>
            /// <param name="filePath">Ruta del fichero donde se guardará la imagen.</param>
            /// <param name="format">Formato con el que se escribirá la imagen.</param>
            public void SaveImage(string filePath, System.Drawing.Imaging.ImageFormat format)
            {
                if (data != null)
                {
                    MemoryStream stream = new MemoryStream(data, 0, data.Length);

                    //System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(stream);

                    //Escribir directamente el array de bytes a un fichero ".jpg"
                    //FileStream fs = new FileStream("c:\\prueba.jpg", FileMode.CreateNew);
                    //BinaryWriter w = new BinaryWriter(fs);
                    //w.Write(image,0,imageSize);
                    //w.Close();
                    //fs.Close();

                    //Escribir a un fichero cualquier tipo de imagen
                    Bitmap bitmap = new Bitmap(stream);
                    bitmap.Save(filePath, format);
                }
            }
Ejemplo n.º 53
0
        public override void Save(Stream stream, ImageFormat format)
        {
            Android.Graphics.Bitmap.CompressFormat compressFormat;
            if (format.Equals(ImageFormat.Jpeg))
            {
                compressFormat = Android.Graphics.Bitmap.CompressFormat.Jpeg;
            }
            else if (format.Equals(ImageFormat.Png))
            {
                compressFormat = Android.Graphics.Bitmap.CompressFormat.Png;
            }
            else
            {
                throw new ArgumentOutOfRangeException("format", format, "Only supported formats are JPEG and PNG");
            }

            var androidBitmap = (Android.Graphics.Bitmap) this;

            androidBitmap.Compress(compressFormat, 100, stream);
        }
Ejemplo n.º 54
0
 /// <summary>
 /// 图片转二进制
 /// </summary>
 /// <param name="image">图片对象</param>
 /// <param name="imageFormat">后缀名</param>
 /// <returns></returns>
 public static byte[] ImageToBytes(Image image, System.Drawing.Imaging.ImageFormat imageFormat)
 {
     if (image == null)
     {
         return(null);
     }
     byte[] data;
     using (MemoryStream ms = new MemoryStream())
     {
         using (Bitmap bitmap = new Bitmap(image))
         {
             bitmap.Save(ms, imageFormat);
             ms.Position = 0;
             data        = new byte[ms.Length];
             ms.Read(data, 0, Convert.ToInt32(ms.Length));
             ms.Flush();
         }
     }
     return(data);
 }
Ejemplo n.º 55
0
        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK != saveDialog.ShowDialog())
                {
                    return;
                }

                System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Png;
                if (saveDialog.FileName.ToLower().EndsWith(".jpg"))
                {
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                }
                if (saveDialog.FileName.ToLower().EndsWith(".jpeg"))
                {
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                }
                else if (saveDialog.FileName.ToLower().EndsWith(".bmp"))
                {
                    format = System.Drawing.Imaging.ImageFormat.Bmp;
                }
                else if (saveDialog.FileName.ToLower().EndsWith(".png"))
                {
                    format = System.Drawing.Imaging.ImageFormat.Png;
                }
                else if (saveDialog.FileName.ToLower().EndsWith(".gif"))
                {
                    format = System.Drawing.Imaging.ImageFormat.Gif;
                }

                Bitmap bmp = new Bitmap(picture.Image);
                bmp.SetResolution(picture.Image.HorizontalResolution, picture.Image.VerticalResolution);

                bmp.Save(saveDialog.FileName, format);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 56
0
        /// <summary>
        /// 放大图像
        /// </summary>
        /// <param name="b">原始图像</param>
        /// <param name="destHeight">目标高度</param>
        /// <param name="destWidth">目标宽度</param>
        /// <returns></returns>
        public static Bitmap EnlargeImage(Image b, float destHeight, float destWidth, bool isDispose = false)
        {
            System.Drawing.Image imgSource = b;
            System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;
            float sW = 0, sH = 0;
            // 按比例缩放
            int sWidth = imgSource.Width;
            int sHeight = imgSource.Height;

            if ((sWidth * destHeight) > (sHeight * destWidth))
            {
                sW = destWidth;
                sH = (destWidth * sHeight) / sWidth;
            }
            else
            {
                sH = destHeight;
                sW = (sWidth * destHeight) / sHeight;
            }
            Bitmap   outBmp = new Bitmap((int)destWidth, (int)destHeight);
            Graphics g = Graphics.FromImage(outBmp);

            g.Clear(Color.Transparent);
            // 设置画布的描绘质量
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.DrawImage(imgSource, new Rectangle((int)((destWidth - sW) / 2), (int)((destHeight - sH) / 2), (int)sW, (int)sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //// 以下代码为保存图片时,设置压缩质量
            //EncoderParameters encoderParams = new EncoderParameters();
            //long[] quality = new long[1];
            //quality[0] = 100;
            //EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            //encoderParams.Param[0] = encoderParam;
            if (isDispose)
            {
                imgSource.Dispose();
            }
            return(outBmp);
        }
Ejemplo n.º 57
0
        public static bool ResizeAndSaveImageProporcional(string pathImageTemp, byte[] file, int MaxWidth, int MaxHeight)
        {
            bool objReturn = false;

            try
            {
                MemoryStream         imageStream               = new MemoryStream(file);
                System.Drawing.Image fullSizeImg               = System.Drawing.Image.FromStream(imageStream);
                System.Drawing.Image AdjustedImage             = ResizeImageProporcional(fullSizeImg, MaxWidth, MaxHeight);
                System.Drawing.Imaging.ImageFormat imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;

                if (AdjustedImage != null)
                {
                    switch (pathImageTemp.Substring(pathImageTemp.Length - 4))
                    {
                    case ".jpg":
                        imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                        break;

                    case ".png":
                        imageFormat = System.Drawing.Imaging.ImageFormat.Png;
                        break;

                    case ".gif":
                        imageFormat = System.Drawing.Imaging.ImageFormat.Gif;
                        break;

                    default:
                        imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                        break;
                    }
                    AdjustedImage.Save(pathImageTemp, imageFormat);
                    AdjustedImage.Dispose();
                    objReturn = true;
                }
                imageStream.Close();
                imageStream.Dispose();
            }
            catch { }
            return(objReturn);
        }
Ejemplo n.º 58
0
        internal static byte[] InsertImageIntoPDF(byte[] file, Image QrImage, Image FontImage, int QPositionX = 30, int QPositionY = 675, int QWidth = 100, int QHeight = 100, int FPositionX = 450, int FPositionY = 50, int FWidth = 130, int FHeight = 15)
        {
            try
            {
                var pdfReader = new iTextSharp.text.pdf.PdfReader(file);
                using (var ms = new MemoryStream())
                {
                    using (var stamp = new iTextSharp.text.pdf.PdfStamper(pdfReader, ms))
                    {
                        var size = pdfReader.GetPageSize(1);
                        var page = pdfReader.NumberOfPages;

                        #region QrCode
                        System.Drawing.Imaging.ImageFormat QrImgformat = FormatImage(QrImage);
                        var pdfQrImage = iTextSharp.text.Image.GetInstance(QrImage, QrImgformat);
                        pdfQrImage.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                        pdfQrImage.SetAbsolutePosition(QPositionX, QPositionY);
                        pdfQrImage.ScaleToFit(QWidth, QHeight);
                        stamp.GetOverContent(page).AddImage(pdfQrImage);
                        #endregion

                        #region Font
                        System.Drawing.Imaging.ImageFormat fontImageFormat = FormatImage(FontImage);
                        var pdfFontImage = iTextSharp.text.Image.GetInstance(FontImage, fontImageFormat);
                        pdfFontImage.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                        pdfFontImage.SetAbsolutePosition(FPositionX, FPositionY);
                        pdfFontImage.ScaleToFit(FWidth, FHeight);
                        stamp.GetOverContent(page).AddImage(pdfFontImage);
                        #endregion
                    }
                    ms.Flush();
                    ms.GetBuffer();

                    return(ms.ToArray());
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 59
0
        /// <summary>
        /// 图片转byte[]
        /// </summary>
        /// <param name="Bitmap"></param>
        /// <param name="imageFormat"></param>
        /// <returns></returns>
        public static byte[] BitmapToBytes(Bitmap Bitmap, System.Drawing.Imaging.ImageFormat imageFormat)
        {
            MemoryStream ms = null;

            try
            {
                ms = new MemoryStream();
                Bitmap.Save(ms, imageFormat);
                byte[] byteImage = new Byte[ms.Length];
                byteImage = ms.ToArray();
                return(byteImage);
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }
        }
Ejemplo n.º 60
0
        private void SaveScreenShot(string path, System.Drawing.Imaging.ImageFormat format)
        {
            var wb = Browser;

            if (!IsKanColleLoaded)
            {
                // AddLog(3, "", "因为", "『艦これ』", "还没有载入,无法截图。");
                System.Media.SystemSounds.Beep.Play();
                return;
            }
            try
            {
                // f**k it, I'll do it on my own.
            }
            catch (Exception ex)
            {
                BrowserHost.AsyncRemoteRun(() =>
                                           BrowserHost.Proxy.SendErrorReport(ex.ToString(), "スクリーンショットの保存時にエラーが発生しました。"));
                System.Media.SystemSounds.Beep.Play();
            }
        }