/// <summary> /// Put an image stream out. Use by Chart and Image /// </summary> /// <param name="ioin"></param> /// <param name="width"></param> /// <param name="height"></param> void PutImage(System.DrawingCore.Image im, int width, int height) { MemoryStream ostrm = new MemoryStream(); ImageFormat imf; imf = ImageFormat.Png; im.Save(ostrm, imf); byte[] ba = ostrm.ToArray(); ostrm.Close(); tw.Write('{'); // convert height/width to twips // ???? not sure what picw pich units should really be?? int h = GetTwipsFromPixels(height <= 0 ? im.Height : height); int w = GetTwipsFromPixels(width <= 0 ? im.Width : width); int imw_twip = GetTwipsFromPixels(im.Width); int imh_twip = GetTwipsFromPixels(im.Height); tw.Write(@"\pict\pngblip\picwgoal{2}\pichgoal{3} ", w, h, imw_twip, imh_twip); //tw.Write(@"\pict\jpegblip\picw423\pich423\picwgoal{2}\pichgoal{3} ", // w, h, imw_twip, imh_twip); foreach (byte b in ba) { tw.Write(HEXCHARS[(byte)((b >> 4) & 0x0f)]); tw.Write(HEXCHARS[(byte)(b & 0x0f)]); } tw.Write('}'); return; }
public void Image(Image i, Row r, string mimeType, Stream ioin) { using (System.DrawingCore.Image im = System.DrawingCore.Image.FromStream(ioin)) { PutImage(im, i.Width == null ? 0 : i.Width.PixelsX, i.Height == null ? 0 : i.Height.PixelsY); } if (InTable(i)) { tw.Write(@"\cell"); } //switch (i.Sizing) //{ // case ImageSizingEnum.AutoSize: // break; // this is right // case ImageSizingEnum.Clip: // break; // not sure how to clip it // case ImageSizingEnum.Fit: // if (h > 0) // sw.Write(" height=\"{0}\"", h.ToString()); // if (w > 0) // sw.Write(" width=\"{0}\"", w.ToString()); // break; // case ImageSizingEnum.FitProportional: // break; // would have to create an image to handle this //} }
/** * Gets the image contents of frame n. * * @return BufferedImage representation of frame, or null if n is invalid. */ public System.DrawingCore.Image GetFrame(int n) { System.DrawingCore.Image im = null; if ((n >= 0) && (n < frameCount)) { im = ((GifFrame)frames[n]).image; } return(im); }
public void Chart(Chart c, Row row, ChartBase cb) { System.DrawingCore.Image im = cb.Image(r); PutImage(im, im.Width, im.Height); if (InTable(c)) { tw.Write(@"\cell"); } }
/** * Resets frame state for reading next image. */ protected void ResetFrame() { lastDispose = dispose; lastRect = new Rectangle(ix, iy, iw, ih); lastImage = image; lastBgColor = bgColor; // int dispose = 0; bool transparency = false; int delay = 0; lct = null; }
public void Create_Gif_Img_To_Png_Test() { var isExists = File.Exists(imageGifPath); Assert.IsTrue(isExists, "文件存在"); AnimatedGifDecoder de = new AnimatedGifDecoder(); de.Read(imageGifPath); for (int i = 0, count = de.GetFrameCount(); i < count; i++) { System.DrawingCore.Image frame = de.GetFrame(i); frame.Save(outputFilePath + Guid.NewGuid().ToString() + ".png"); } }
/// <summary> /// 生成图片缩略图 /// </summary> /// <param name="sourcePath">图片路径</param> /// <param name="newPath">新图片路径</param> /// <param name="width">宽度</param> /// <param name="height">高度</param> public static void MakeThumbnail(string sourcePath, string newPath, int width, int height) { System.DrawingCore.Image ig = System.DrawingCore.Image.FromFile(sourcePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = ig.Width; int oh = ig.Height; if ((double)ig.Width / (double)ig.Height > (double)towidth / (double)toheight) { oh = ig.Height; ow = ig.Height * towidth / toheight; y = 0; x = (ig.Width - ow) / 2; } else { ow = ig.Width; oh = ig.Width * height / towidth; x = 0; y = (ig.Height - oh) / 2; } System.DrawingCore.Image bitmap = new System.DrawingCore.Bitmap(towidth, toheight); System.DrawingCore.Graphics g = System.DrawingCore.Graphics.FromImage(bitmap); g.InterpolationMode = System.DrawingCore.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.DrawingCore.Drawing2D.SmoothingMode.HighQuality; g.Clear(System.DrawingCore.Color.Transparent); g.DrawImage(ig, new System.DrawingCore.Rectangle(0, 0, towidth, toheight), new System.DrawingCore.Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); try { bitmap.Save(newPath, System.DrawingCore.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { throw ex; } finally { ig.Dispose(); bitmap.Dispose(); g.Dispose(); } }
private void DrawImage(PageImage pi, Graphics g, RectangleF r) { Stream strm = null; System.DrawingCore.Image im = null; try { strm = new MemoryStream(pi.ImageData); im = System.DrawingCore.Image.FromStream(strm); DrawImageSized(pi, im, g, r); } finally { if (strm != null) { strm.Close(); } if (im != null) { im.Dispose(); } } }
public GifFrame(System.DrawingCore.Image im, int del) { image = im; delay = del; }
/** * Reads next frame image */ protected void ReadImage() { ix = ReadShort(); // (sub)image position & size iy = ReadShort(); iw = ReadShort(); ih = ReadShort(); int packed = Read(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size if (lctFlag) { lct = ReadColorTable(lctSize); // read table act = lct; // make local table active } else { act = gct; // make global table active if (bgIndex == transIndex) { bgColor = 0; } } int save = 0; if (transparency) { save = act[transIndex]; act[transIndex] = 0; // set transparent color if specified } if (act == null) { status = STATUS_FORMAT_ERROR; // no color table defined } if (Error()) { return; } DecodeImageData(); // decode pixel data Skip(); if (Error()) { return; } frameCount++; // create new image to receive frame data // image = // new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); bitmap = new Bitmap(width, height); image = bitmap; SetPixels(); // transfer pixel data to image frames.Add(new GifFrame(bitmap, delay)); // add image to frame list if (transparency) { act[transIndex] = save; } ResetFrame(); }
protected void SetPixels() { // expose destination image's pixels as int array // int[] dest = // (( int ) image.getRaster().getDataBuffer()).getData(); int[] dest = GetPixels(bitmap); // fill in starting image contents based on last image's dispose code if (lastDispose > 0) { if (lastDispose == 3) { // use image before last int n = frameCount - 2; if (n > 0) { lastImage = GetFrame(n - 1); } else { lastImage = null; } } if (lastImage != null) { // int[] prev = // ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData(); int[] prev = GetPixels(new Bitmap(lastImage)); Array.Copy(prev, 0, dest, 0, width * height); // copy pixels if (lastDispose == 2) { // fill last image rect area with background color Graphics g = Graphics.FromImage(image); Color c = Color.Empty; if (transparency) { c = Color.FromArgb(0, 0, 0, 0); // assume background is transparent } else { c = Color.FromArgb(lastBgColor); // c = new Color(lastBgColor); // use given background color } Brush brush = new SolidBrush(c); g.FillRectangle(brush, lastRect); brush.Dispose(); g.Dispose(); } } } // copy each source line to the appropriate place in the destination int pass = 1; int inc = 8; int iline = 0; for (int i = 0; i < ih; i++) { int line = i; if (interlace) { if (iline >= ih) { pass++; switch (pass) { case 2: iline = 4; break; case 3: iline = 2; inc = 4; break; case 4: iline = 1; inc = 2; break; } } line = iline; iline += inc; } line += iy; if (line < height) { int k = line * width; int dx = k + ix; // start of line in dest int dlim = dx + iw; // end of dest line if ((k + width) < dlim) { dlim = k + width; // past dest edge } int sx = i * iw; // start of line in source while (dx < dlim) { // map color and insert in destination int index = ((int)pixels[sx++]) & 0xff; int c = act[index]; if (c != 0) { dest[dx] = c; } dx++; } } } SetPixels(dest); }
private PageImage BuildImage(Graphics g, string token, StyleInfo oldsi, PageText model) { PageTextHtmlCmdLexer hc = new PageTextHtmlCmdLexer(token.Substring(4)); Hashtable ht = hc.Lex(); string src = (string)ht["src"]; if (src == null || src.Length < 1) { return(null); } string alt = (string)ht["alt"]; string height = (string)ht["height"]; string width = (string)ht["width"]; string align = (string)ht["align"]; Stream strm = null; System.DrawingCore.Image im = null; PageImage pi = null; try { // Obtain the image stream if (src.StartsWith("http:") || src.StartsWith("file:") || src.StartsWith("https:")) { WebRequest wreq = WebRequest.Create(src); WebResponse wres = wreq.GetResponse(); strm = wres.GetResponseStream(); } else { strm = new FileStream(src, System.IO.FileMode.Open, FileAccess.Read); } im = System.DrawingCore.Image.FromStream(strm); int h = im.Height; int w = im.Width; MemoryStream ostrm = new MemoryStream(); ImageFormat imf; imf = ImageFormat.Jpeg; im.Save(ostrm, imf); byte[] ba = ostrm.ToArray(); ostrm.Close(); pi = new PageImage(imf, ba, w, h); pi.AllowSelect = false; pi.Page = this.Page; pi.HyperLink = model.HyperLink; pi.Tooltip = alt == null ? model.Tooltip : alt; pi.X = 0; pi.Y = 0; pi.W = RSize.PointsFromPixels(g, width != null? Convert.ToInt32(width): w); pi.H = RSize.PointsFromPixels(g, height != null? Convert.ToInt32(height): h); pi.SI = new StyleInfo(); } catch { pi = null; } finally { if (strm != null) { strm.Close(); } if (im != null) { im.Dispose(); } } return(pi); }
override internal void RunPage(Pages pgs, Row row) { Report r = pgs.Report; bool bHidden = IsHidden(r, row); WorkClass wc = GetWC(r); string mtype = null; Stream strm = null; System.DrawingCore.Image im = null; SetPagePositionBegin(pgs); if (bHidden) { PageImage pi = new PageImage(ImageFormat.Jpeg, null, 0, 0); this.SetPagePositionAndStyle(r, pi, row); SetPagePositionEnd(pgs, pi.Y + pi.H); return; } if (wc.PgImage != null) { // have we already generated this one // reuse most of the work; only position will likely change PageImage pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH); pi.Name = wc.PgImage.Name; // this is name it will be shared under pi.Sizing = this._Sizing; this.SetPagePositionAndStyle(r, pi, row); pgs.CurrentPage.AddObject(pi); SetPagePositionEnd(pgs, pi.Y + pi.H); return; } try { strm = GetImageStream(r, row, out mtype); if (strm == null) { r.rl.LogError(4, string.Format("Unable to load image {0}.", this.Name.Nm)); return; } im = System.DrawingCore.Image.FromStream(strm); int height = im.Height; int width = im.Width; MemoryStream ostrm = new MemoryStream(); strm.Position = 0; ImageFormat imf; switch (mtype.ToLower()) { case "image/jpeg": imf = ImageFormat.Jpeg; CopyStream(strm, ostrm); break; case "image/png": imf = ImageFormat.Png; CopyStream(strm, ostrm); break; default: // from old code where all images convert to jpeg, i don't know why. May be need delete it and add all support formats. imf = ImageFormat.Jpeg; System.DrawingCore.Imaging.ImageCodecInfo[] info; info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.EmbeddedImageQuality); System.DrawingCore.Imaging.ImageCodecInfo codec = null; for (int i = 0; i < info.Length; i++) { if (info[i].FormatDescription == "JPEG") { codec = info[i]; break; } } im.Save(ostrm, codec, encoderParameters); break; } byte[] ba = ostrm.ToArray(); ostrm.Close(); PageImage pi = new PageImage(imf, ba, width, height); pi.Sizing = this._Sizing; this.SetPagePositionAndStyle(r, pi, row); pgs.CurrentPage.AddObject(pi); if (_ConstantImage) { wc.PgImage = pi; // create unique name; PDF generation uses this to optimize the saving of the image only once pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name } SetPagePositionEnd(pgs, pi.Y + pi.H); } catch (Exception e) { // image failed to load, continue processing r.rl.LogError(4, "Image load failed. " + e.Message); } finally { if (strm != null) { strm.Close(); } if (im != null) { im.Dispose(); } } return; }
private void DrawImageSized(PageImage pi, System.DrawingCore.Image im, System.DrawingCore.Graphics g, System.DrawingCore.RectangleF r) { float height, width; // some work variables StyleInfo si = pi.SI; // adjust drawing rectangle based on padding System.DrawingCore.RectangleF r2 = new System.DrawingCore.RectangleF(r.Left + PixelsX(si.PaddingLeft), r.Top + PixelsY(si.PaddingTop), r.Width - PixelsX(si.PaddingLeft + si.PaddingRight), r.Height - PixelsY(si.PaddingTop + si.PaddingBottom)); System.DrawingCore.Rectangle ir; // int work rectangle switch (pi.Sizing) { case ImageSizingEnum.AutoSize: // Note: GDI+ will stretch an image when you only provide // the left/top coordinates. This seems pretty stupid since // it results in the image being out of focus even though // you don't want the image resized. if (g.DpiX == im.HorizontalResolution && g.DpiY == im.VerticalResolution) { ir = new System.DrawingCore.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), im.Width, im.Height); } else { ir = new System.DrawingCore.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height)); } g.DrawImage(im, ir); break; case ImageSizingEnum.Clip: Region saveRegion = g.Clip; Region clipRegion = new Region(g.Clip.GetRegionData()); clipRegion.Intersect(r2); g.Clip = clipRegion; if (g.DpiX == im.HorizontalResolution && g.DpiY == im.VerticalResolution) { ir = new System.DrawingCore.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), im.Width, im.Height); } else { ir = new System.DrawingCore.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height)); } g.DrawImage(im, ir); g.Clip = saveRegion; break; case ImageSizingEnum.FitProportional: float ratioIm = (float)im.Height / (float)im.Width; float ratioR = r2.Height / r2.Width; height = r2.Height; width = r2.Width; if (ratioIm > ratioR) { // this means the rectangle width must be corrected width = height * (1 / ratioIm); } else if (ratioIm < ratioR) { // this means the ractangle height must be corrected height = width * ratioIm; } r2 = new RectangleF(r2.X, r2.Y, width, height); g.DrawImage(im, r2); break; case ImageSizingEnum.Fit: default: g.DrawImage(im, r2); break; } return; }
private void DrawImageSized(PageImage pi, System.DrawingCore.Image im, Graphics g, RectangleF r) { float height, width; // some work variables StyleInfo si = pi.SI; // adjust drawing rectangle based on padding // http://www.fyireporting.com/forum/viewtopic.php?t=892 //A.S.> convert pt to px if needed(when printing we need px, when draw preview - pt) RectangleF r2; if (g.PageUnit == GraphicsUnit.Pixel) { r2 = new RectangleF(r.Left + (si.PaddingLeft * g.DpiX) / 72, r.Top + (si.PaddingTop * g.DpiX) / 72, r.Width - ((si.PaddingLeft + si.PaddingRight) * g.DpiX) / 72, r.Height - ((si.PaddingTop + si.PaddingBottom) * g.DpiX) / 72); } else { // adjust drawing rectangle based on padding r2 = new RectangleF(r.Left + si.PaddingLeft, r.Top + si.PaddingTop, r.Width - si.PaddingLeft - si.PaddingRight, r.Height - si.PaddingTop - si.PaddingBottom); } System.DrawingCore.Rectangle ir; // int work rectangle ir = new System.DrawingCore.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height)); switch (pi.Sizing) { case ImageSizingEnum.AutoSize: // Note: GDI+ will stretch an image when you only provide // the left/top coordinates. This seems pretty stupid since // it results in the image being out of focus even though // you don't want the image resized. if (g.DpiX == im.HorizontalResolution && g.DpiY == im.VerticalResolution) { ir = new System.DrawingCore.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), im.Width, im.Height); } g.DrawImage(im, ir); break; case ImageSizingEnum.Clip: Region saveRegion = g.Clip; Region clipRegion = new Region(g.Clip.GetRegionData()); clipRegion.Intersect(r2); g.Clip = clipRegion; if (g.DpiX == im.HorizontalResolution && g.DpiY == im.VerticalResolution) { ir = new System.DrawingCore.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), im.Width, im.Height); } g.DrawImage(im, ir); g.Clip = saveRegion; break; case ImageSizingEnum.FitProportional: float ratioIm = (float)im.Height / (float)im.Width; float ratioR = r2.Height / r2.Width; height = r2.Height; width = r2.Width; if (ratioIm > ratioR) { // this means the rectangle width must be corrected width = height * (1 / ratioIm); } else if (ratioIm < ratioR) { // this means the ractangle height must be corrected height = width * ratioIm; } r2 = new RectangleF(r2.X, r2.Y, width, height); g.DrawImage(im, r2); break; case ImageSizingEnum.Fit: default: g.DrawImage(im, r2); break; } //if (SelectTool && pi.AllowSelect && _SelectList.Contains(pi)) //{ // g.FillRectangle(new SolidBrush(Color.FromArgb(50, _SelectItemColor)), ir); //} return; }
private void DrawImageBackground(PageImage pi, StyleInfo si, Graphics g, RectangleF r) { Stream strm = null; System.DrawingCore.Image im = null; try { strm = new MemoryStream(pi.ImageData); im = System.DrawingCore.Image.FromStream(strm); // http://www.fyireporting.com/forum/viewtopic.php?t=892 //A.S.> convert pt to px if needed(when printing we need px, when draw preview - pt) RectangleF r2; if (g.PageUnit == GraphicsUnit.Pixel) { r2 = new RectangleF(r.Left + (si.PaddingLeft * g.DpiX) / 72, r.Top + (si.PaddingTop * g.DpiX) / 72, r.Width - ((si.PaddingLeft + si.PaddingRight) * g.DpiX) / 72, r.Height - ((si.PaddingTop + si.PaddingBottom) * g.DpiX) / 72); } else { // adjust drawing rectangle based on padding r2 = new RectangleF(r.Left + si.PaddingLeft, r.Top + si.PaddingTop, r.Width - si.PaddingLeft - si.PaddingRight, r.Height - si.PaddingTop - si.PaddingBottom); } int repeatX = 0; int repeatY = 0; switch (pi.Repeat) { case ImageRepeat.Repeat: repeatX = (int)Math.Floor(r2.Width / pi.SamplesW); repeatY = (int)Math.Floor(r2.Height / pi.SamplesH); break; case ImageRepeat.RepeatX: repeatX = (int)Math.Floor(r2.Width / pi.SamplesW); repeatY = 1; break; case ImageRepeat.RepeatY: repeatY = (int)Math.Floor(r2.Height / pi.SamplesH); repeatX = 1; break; case ImageRepeat.NoRepeat: default: repeatX = repeatY = 1; break; } //make sure the image is drawn at least 1 times repeatX = Math.Max(repeatX, 1); repeatY = Math.Max(repeatY, 1); float startX = r2.Left; float startY = r2.Top; Region saveRegion = g.Clip; Region clipRegion = new Region(g.Clip.GetRegionData()); clipRegion.Intersect(r2); g.Clip = clipRegion; for (int i = 0; i < repeatX; i++) { for (int j = 0; j < repeatY; j++) { float currX = startX + i * pi.SamplesW; float currY = startY + j * pi.SamplesH; g.DrawImage(im, new RectangleF(currX, currY, pi.SamplesW, pi.SamplesH)); } } g.Clip = saveRegion; } finally { if (strm != null) { strm.Close(); } if (im != null) { im.Dispose(); } } }
/// <summary> /// 增加图片文字水印 /// </summary> /// <param name="filename">文件名</param> /// <param name="watermarkText">水印文字</param> /// <param name="watermarkStatus">图片水印位置</param> public static void AddImageSignText(System.DrawingCore.Image img, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize) { Graphics g = Graphics.FromImage(img); Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel); SizeF crSize; crSize = g.MeasureString(watermarkText, drawFont); float xpos = 0; float ypos = 0; switch (watermarkStatus) { case 1: xpos = (float)img.Width * (float).01; ypos = (float)img.Height * (float).01; break; case 2: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = (float)img.Height * (float).01; break; case 3: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = (float)img.Height * (float).01; break; case 4: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 5: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 6: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 7: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 8: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 9: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).99) - crSize.Height; break; } g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1); g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) { ici = codec; } } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.DrawingCore.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) { img.Save(filename, ici, encoderParams); } else { img.Save(filename); } g.Dispose(); img.Dispose(); }
/// <summary> /// 生成缩略图到MemoryStream /// </summary> /// <param name="SourceFile"></param> /// <param name="intThumbWidth"></param> /// <param name="intThumbHeight"></param> /// <param name="gap">是否补足空白</param> public static MemoryStream ThumbImageToStream(string SourceFile, int intThumbWidth, int intThumbHeight, bool gap = true) { MemoryStream ms = new MemoryStream(); //原图加载 using (System.DrawingCore.Image sourceImage = System.DrawingCore.Image.FromFile(SourceFile)) { //是否显示原图 if (intThumbWidth == 0 && intThumbHeight == 0) { sourceImage.Save(ms, System.DrawingCore.Imaging.ImageFormat.Png); return(ms); } //原图宽度和高度 int width = sourceImage.Width; int height = sourceImage.Height; int smallWidth; int smallHeight; //如果原图长宽均比缩略图的要小则返回原stream if (width <= intThumbWidth && height <= intThumbHeight) { sourceImage.Save(ms, System.DrawingCore.Imaging.ImageFormat.Png); return(ms); } //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高) if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight) { smallWidth = intThumbHeight * width / height; smallHeight = intThumbHeight; } else { smallWidth = intThumbWidth; smallHeight = intThumbWidth * height / width; } Image newimg = sourceImage.GetThumbnailImage(smallWidth, smallHeight, null, IntPtr.Zero); //使用原宽高比输出,不补足空白 if (!gap) { newimg.Save(ms, System.DrawingCore.Imaging.ImageFormat.Png); return(ms); } //新建一个图板,以最小等比例压缩大小绘制原图 using (System.DrawingCore.Image bitmap = new System.DrawingCore.Bitmap(smallWidth, smallHeight)) { //绘制中间图 using (System.DrawingCore.Graphics g = System.DrawingCore.Graphics.FromImage(bitmap)) { //高清,平滑 g.InterpolationMode = System.DrawingCore.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.DrawingCore.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Transparent); g.DrawImage( sourceImage, new System.DrawingCore.Rectangle(0, 0, smallWidth, smallHeight), new System.DrawingCore.Rectangle(0, 0, width, height), System.DrawingCore.GraphicsUnit.Pixel ); } //新建一个图板,以缩略图大小绘制中间图 using (System.DrawingCore.Image bitmap1 = new System.DrawingCore.Bitmap(intThumbWidth, intThumbHeight)) { //绘制缩略图 using (System.DrawingCore.Graphics g = System.DrawingCore.Graphics.FromImage(bitmap1)) { //高清,平滑 g.InterpolationMode = System.DrawingCore.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.DrawingCore.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Transparent); int lwidth = (smallWidth - intThumbWidth) / 2; int bheight = (smallHeight - intThumbHeight) / 2; g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel); g.Dispose(); bitmap1.Save(ms, System.DrawingCore.Imaging.ImageFormat.Png); return(ms); } } } } }