public void Preview(Surface surface, SGraphics g) { g.DrawImage(Brush.Bitmap, surface.TileSet.TileSize * surface.GetBrushLocation().X * surface.Zoom + surface.GetOffset().X, surface.TileSet.TileSize * surface.GetBrushLocation().Y * surface.Zoom + surface.GetOffset().Y, Brush.Bitmap.Width * surface.Zoom, Brush.Bitmap.Height * surface.Zoom); }
public void Preview(Surface surface, SGraphics g) { g.DrawImage(brushTemplate.Bitmap, surface.TileSetRenderer.TileSize * surface.GetBrushLocation().X * surface.Zoom + surface.GetOffset().X, surface.TileSetRenderer.TileSize * surface.GetBrushLocation().Y * surface.Zoom + surface.GetOffset().Y, brushTemplate.Bitmap.Width * surface.Zoom, brushTemplate.Bitmap.Height * surface.Zoom); }
/// <summary> /// 从图片中截取部分生成新图 /// </summary> /// <param name="sFromFilePath">原始图片</param> /// <param name="saveFilePath">生成新图</param> /// <param name="width">截取图片宽度</param> /// <param name="height">截取图片高度</param> /// <param name="spaceX">截图图片X坐标</param> /// <param name="spaceY">截取图片Y坐标</param> public void CaptureImage(string sFromFilePath, string saveFilePath, int width, int height, int spaceX, int spaceY, string tarimg, string targetID) { //载入底图 System.Drawing.Image fromImage = System.Drawing.Image.FromFile(sFromFilePath); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height); //创建作图区域 System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap); //截取原图相应区域写入作图区 graphic.DrawImage(fromImage, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(spaceX, spaceY, width, height), System.Drawing.GraphicsUnit.Pixel); //从作图区生成新图 System.Drawing.Image saveImage = System.Drawing.Image.FromHbitmap(bitmap.GetHbitmap()); //保存图象 saveImage.Save(saveFilePath, ImageFormat.Jpeg); bitmap.Dispose(); graphic.Dispose(); saveImage.Dispose(); fromImage.Dispose(); //string delTarget = tarimg.Replace("nail.", "."); //FileHelper.DeleteFile(new List<string> { delTarget });//删除原图 FileHelper.DeleteFile(new List <string> { tarimg }); //删除原图 string delTarget = saveFilePath.Replace(Server.MapPath("/"), ""); //FileInfo fileInfo = new FileInfo(saveFilePath); //fileInfo.MoveTo(sFromFilePath); if (makeNail == 1)//是否需要生成缩略图 { string makeFile = string.Empty; //if (targetType == 0) //{ Dictionary <int, int> dic = new Dictionary <int, int>(); if (tableID == ProductBLL.TableID) { foreach (var phototype in PhotoSizeBLL.SearchList((int)PhotoType.Product)) { dic.Add(phototype.Width, phototype.Height); } if (!dic.ContainsKey(90)) { dic.Add(90, 90); //后台商品列表默认使用尺寸(如果不存在则手动添加) } } else if (tableID == ProductBrandBLL.TableID) { dic.Add(88, 31); } else if (tableID == ThemeActivityBLL.TableID) { dic.Add(300, 150); } else if (tableID == ArticleBLL.TableID) { dic.Add(90, 90); //后台列表缩略图 dic.Add(200, 150); //前台列表缩略图 } else if (tableID == ProductPhotoBLL.TableID) { foreach (var phototype in PhotoSizeBLL.SearchList((int)PhotoType.ProductPhoto)) { dic.Add(phototype.Width, phototype.Height); } if (!dic.ContainsKey(75)) { dic.Add(75, 75); //后台商品图集默认使用尺寸(如果不存在则手动添加) } } if (dic.Count > 0) { foreach (KeyValuePair <int, int> kv in dic) { //string nailStr = delTarget.Replace("Original", kv.Key.ToString() + "-" + kv.Value.ToString()); string nailStr = tarimg.Replace("Original", kv.Key.ToString() + "-" + kv.Value.ToString()); FileHelper.DeleteFile(new List <string> { nailStr }); //删除原有缩略图 //makeFile = nailStr; makeFile = delTarget.Replace("Original", kv.Key.ToString() + "-" + kv.Value.ToString()); ImageHelper.MakeThumbnailImage(ServerHelper.MapPath(delTarget), ServerHelper.MapPath(makeFile), kv.Key, kv.Value, ThumbnailType.InBox); } } //} //else //{ // Hashtable ht = new Hashtable(); // if (tableID == ProductPhotoBLL.TableID) // { // foreach (var phototype in PhotoSizeBLL.SearchList((int)PhotoType.ProductPhoto)) // { // ht.Add(phototype.Width, phototype.Height); // } // if (!ht.ContainsKey(75)) ht.Add(75, 75);//后台商品图集默认使用尺寸(如果不存在则手动添加) // } // else // { // ht.Add("75", "75"); // ht.Add("350", "350"); // } // foreach (DictionaryEntry de in ht) // { // string nailStr = delTarget.Replace("Original", de.Key + "-" + de.Value); // FileHelper.DeleteFile(new List<string> { nailStr });//删除原有缩略图 // makeFile = nailStr; // ImageHelper.MakeThumbnailImage(ServerHelper.MapPath(delTarget), ServerHelper.MapPath(makeFile), Convert.ToInt32(de.Key), Convert.ToInt32(de.Value), ThumbnailType.InBox); // } //} } //parent.layer.close(index); string strp_img2 = saveFilePath.Substring(saveFilePath.LastIndexOf('/'), saveFilePath.Length - saveFilePath.LastIndexOf('/')); if (targetType == 1)//产品多图 { if (ProductID <= 0) {//添加 //Response.Write("<script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name); parent.$('#" + targetID + ">img').attr('src','" + delTarget + "'); parent.layer.close(index);</script>"); string _str = "<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.editProductPhoto('" + targetID + "', '" + delTarget + "', '" + ProductPhotoID + "');parent.layer.close(index);</script>"; //Response.Write("<script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.o('" + targetID + "').firstChild.src='" + delTarget + "';window.parent.o('" + targetID + "').getElementsByName('ProductPhoto')[0].value='" + _name + "|" + delTarget + "' ; parent.layer.close(index);</script>"); Response.Write("<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.editProductPhoto('" + targetID + "', '" + delTarget + "', '" + ProductPhotoID + "');parent.layer.close(index);</script>"); } else { ProductPhotoInfo productPhoto = ProductPhotoBLL.Read(ProductPhotoID, ProStyle); productPhoto.ImageUrl = delTarget; ProductPhotoBLL.Update(productPhoto); string _str = "<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.editProductPhoto('" + targetID + "', '" + delTarget + "', '" + ProductPhotoID + "');parent.layer.close(index);</script>"; //Response.Write("<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.o('" + targetID + "').firstChild.src='" + delTarget + "';$('#" + targetID + "').find('.cut').attr('href','javascript:loadCut(\"" + delTarget + "\",\"" + targetID + "\",\"" + ProductPhotoID + "\")');parent.layer.close(index);</script>"); Response.Write("<script type='text/javascript' src='/Admin/Js/jquery-1.7.2.min.js'></script><script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.editProductPhoto('" + targetID + "', '" + delTarget + "', '" + ProductPhotoID + "');parent.layer.close(index);</script>"); } } else { Response.Write("<script>alert('裁剪成功');var index = parent.layer.getFrameIndex(window.name);window.parent.o('" + targetID + "').value='" + delTarget + "';window.parent.o('firstPhoto').src='" + delTarget + "';parent.layer.close(index); </script>"); } }
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "YS": //不改变图片大小直接压缩 towidth = originalImage.Width; toheight = originalImage.Height; break; case "HW": //指定高宽缩放(能够变形) break; case "W": //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut": //指定高宽扩充(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; case "C": //按原图比例缩放 if (((double)originalImage.Width < (double)towidth) && ((double)originalImage.Height < (double)toheight)) //图片小于外框尺寸,不做处理 { ow = originalImage.Width; oh = originalImage.Height; x = (towidth - ow) / 2; y = (toheight - oh) / 2; } else { if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } else { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度出现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以通明背风光填充 g.Clear(System.Drawing.Color.White); //在指定地位并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //以jpg格式保存缩略图 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } }
private static int MakePic(string sourceImg, string toPath, int pW, int pH) { System.Drawing.Image originalImage = null; System.Drawing.Image bitmap = null; System.Drawing.Graphics g = null; try { originalImage = System.Drawing.Image.FromFile(sourceImg); int oW = originalImage.Width; //原始图片宽 int oH = originalImage.Height; //原始图片高 int tW = oW; //最终显示到页面宽 int tH = oH; //最终显示到页面高 if (oW > pW) //如果原始宽度大于固定宽度 { tW = pW; //最终的宽度等于固定的宽度 tH = pW * oH / oW; //最终的高度等于固定宽度乘以原始高度除以原始宽度 if (tH > pH) { tH = pH; tW = pH * oW / oH;//最终的宽度等于固定高度乘以原始宽度除以原始高度 } } else if (oW < pW)//如果原始宽度小于固定宽度 { tW = oW; if (oH > pH) { tH = pH; tW = pH * oW / oH;//最终的宽度等于固定高度乘以原始宽度除以原始高度 } } else//如果原始宽度等于固定宽度 { if (oH > pH) { tH = pH; tW = pH * oW / oH;//最终的宽度等于固定高度乘以原始宽度除以原始高度 } if (oH < pH) { tH = oH; tW = pH * oW / oH;//最终的宽度等于固定高度乘以原始宽度除以原始高度 } if (oH == pH) { tH = oH; tW = oW; } } //新建一个bmp图片 bitmap = new System.Drawing.Bitmap(tW, tH); //新建一个画板 g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, tW, tH), new System.Drawing.Rectangle(0, 0, oW, oH), System.Drawing.GraphicsUnit.Pixel); //以jpg格式保存缩略图 bitmap.Save(toPath, System.Drawing.Imaging.ImageFormat.Jpeg); return(1); } catch { throw; } finally { if (originalImage != null) { originalImage.Dispose(); } if (bitmap != null) { bitmap.Dispose(); } if (g != null) { g.Dispose(); } } }
public System.Drawing.Bitmap CombineBitmap(string[] files) { //read all images into memory List <System.Drawing.Bitmap> images = new List <System.Drawing.Bitmap>(); System.Drawing.Bitmap finalImage = null; try { int width = 0; int height = 0; foreach (string image in files) { //create a Bitmap from the file and add it to the list System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image); //update the size of the final bitmap //width += bitmap.Width; //height = bitmap.Height > height ? bitmap.Height : height; height += bitmap.Height; width = bitmap.Width > width ? bitmap.Width : width; images.Add(bitmap); } //create a bitmap to hold the combined image finalImage = new System.Drawing.Bitmap(width, height); //get a graphics object from the image so we can draw on it using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage)) { //set background color g.Clear(System.Drawing.Color.Black); //go through each image and draw it on the final image int offset = 0; foreach (System.Drawing.Bitmap image in images) { g.DrawImage(image, new System.Drawing.Rectangle(0, offset, image.Width, image.Height)); offset += image.Height; } } return(finalImage); } catch (Exception) { if (finalImage != null) { finalImage.Dispose(); } //throw ex; throw; } finally { //clean up memory foreach (System.Drawing.Bitmap image in images) { image.Dispose(); } } }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="photoWidth">缩略图宽度</param> /// <param name="photoHeight">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> /// <code>HW:指定高宽缩放(可能变形)</code> /// <code>W:指定宽,高按比例 </code> /// <code>H:指定高,宽按比例</code> /// <code>CUT:指定高宽裁减(不变形) </code> /// <code>FILL:填充</code> /// <param name="retwidth">返回缩略图宽度</param> /// <param name="retheight">返回缩略图高度</param> /// <returns></returns> public static bool LocalImage2Thumbs2(string originalImagePath, string thumbnailPath, int photoWidth, int photoHeight, string mode, ref int retwidth, ref int retheight) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); #region 开始画图 int lastPhotoWidth = photoWidth; //最后缩略图的宽度 int lastPhotoHeight = photoHeight; //最后缩略图的高度 int toWidth = photoWidth; //原图片被压缩的宽度 int toHeight = photoHeight; //原图片被压缩的高度 int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; int bg_x = 0; int bg_y = 0; switch (mode.ToUpper()) { case "FILL": //压缩填充至指定区域 toHeight = photoHeight; toWidth = toHeight * ow / oh; if (toWidth > photoWidth) { toHeight = toHeight * photoWidth / toWidth; toWidth = photoWidth; } bg_x = (photoWidth - toWidth) / 2; bg_y = (photoHeight - toHeight) / 2; break; case "HW": //指定高宽缩放(可能变形) break; case "W": //指定宽,高按比例 toHeight = lastPhotoHeight = originalImage.Height * photoWidth / originalImage.Width; break; case "H": //指定高,宽按比例 toWidth = lastPhotoWidth = originalImage.Width * photoHeight / originalImage.Height; break; case "CUT": //指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)lastPhotoWidth / (double)lastPhotoHeight) { oh = originalImage.Height; ow = originalImage.Height * lastPhotoWidth / lastPhotoHeight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * photoHeight / lastPhotoWidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } if (photoWidth > originalImage.Width) { toWidth = lastPhotoWidth = originalImage.Width; //最后缩略图的宽度 toHeight = lastPhotoHeight = originalImage.Height; //最后缩略图的高度 } retwidth = lastPhotoWidth; retheight = lastPhotoHeight; System.Drawing.Image bitmap = new System.Drawing.Bitmap(lastPhotoWidth, lastPhotoHeight); //新建一个bmp图片 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //新建一个画板 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //设置高质量,低速度呈现平滑程度 g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.Clear(System.Drawing.Color.White); //白色 g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, toWidth, toHeight), //在指定位置并且按指定大小绘制原图片的指定部分 new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { bitmap.Dispose(); g.Dispose(); } #endregion originalImage.Dispose(); return(true); }
/// <summary> /// 缩放图像 /// </summary> /// <param name="originalImagePath">图片原始路径</param> /// <param name="thumNailPath">保存路径</param> /// <param name="width">缩放图的宽</param> /// <param name="height">缩放图的高</param> /// <param name="model">缩放模式</param> public static void MakeThumNail(string originalImagePath, string thumNailPath, int width, int height, string model) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); int thumWidth = width; //缩略图的宽度 int thumHeight = height; //缩略图的高度 int x = 0; int y = 0; int originalWidth = originalImage.Width; //原始图片的宽度 int originalHeight = originalImage.Height; //原始图片的高度 switch (model) { case "HW": //指定高宽缩放,可能变形 break; case "W": //指定宽度,高度按照比例缩放 thumHeight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高度,宽度按照等比例缩放 thumWidth = originalImage.Width * height / originalImage.Height; break; case "Cut": if ((double)originalImage.Width / (double)originalImage.Height > (double)thumWidth / (double)thumHeight) { originalHeight = originalImage.Height; originalWidth = originalImage.Height * thumWidth / thumHeight; y = 0; x = (originalImage.Width - originalWidth) / 2; } else { originalWidth = originalImage.Width; originalHeight = originalWidth * height / thumWidth; x = 0; y = (originalImage.Height - originalHeight) / 2; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(thumWidth, thumHeight); //新建一个画板 System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap); //设置高质量查值法 graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 graphic.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 graphic.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumWidth, thumHeight), new System.Drawing.Rectangle(x, y, originalWidth, originalHeight), System.Drawing.GraphicsUnit.Pixel); try { bitmap.Save(thumNailPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { throw ex; } finally { originalImage.Dispose(); bitmap.Dispose(); graphic.Dispose(); File.Delete(originalImagePath); } }
public System.Drawing.Image GetSizedImage(int width, int height) { if ((Sizing == Rdl.Engine.Image.ImageSizingEnum.Clip || Sizing == Rdl.Engine.Image.ImageSizingEnum.Fit || Sizing == Rdl.Engine.Image.ImageSizingEnum.FitProportional) && width > 0 && height > 0) { // Create a new bitmap for the image System.Drawing.Bitmap bm = null; System.Drawing.Rectangle sourceRect = System.Drawing.Rectangle.Empty; System.Drawing.Rectangle destRect = System.Drawing.Rectangle.Empty; if (Sizing == Rdl.Engine.Image.ImageSizingEnum.Clip) { bm = new System.Drawing.Bitmap(width, height); // Create the clipping rectangles int xAdj = (width > imageData.Width) ? 0 : ((imageData.Width - width) / 2); int yAdj = (height > imageData.Height) ? 0 : ((imageData.Height - height) / 2); sourceRect = new System.Drawing.Rectangle(xAdj, yAdj, imageData.Width - xAdj, imageData.Height - yAdj); xAdj = (imageData.Width > width) ? 0 : ((width - imageData.Width) / 2); yAdj = (imageData.Height > height) ? 0 : ((height - imageData.Height) / 2); destRect = new System.Drawing.Rectangle(xAdj, yAdj, width - xAdj, height - yAdj); } if (Sizing == Rdl.Engine.Image.ImageSizingEnum.Fit) { bm = new System.Drawing.Bitmap(width, height); // Resize the whole image to the full size of the box. sourceRect = new System.Drawing.Rectangle(0, 0, imageData.Width, imageData.Height); destRect = new System.Drawing.Rectangle(0, 0, width, height); } if (Sizing == Rdl.Engine.Image.ImageSizingEnum.FitProportional) { // Resize the image proportionally to fit the box. sourceRect = new System.Drawing.Rectangle(0, 0, imageData.Width, imageData.Height); int xAdj = 0; int yAdj = 0; float f1 = (float)imageData.Width / (float)imageData.Height; float f2 = (float)width / (float)height; if (f1 > f2) { yAdj = (height - (int)((float)width / f1)); } else { xAdj = (width - (int)((float)height * f1)); } bm = new System.Drawing.Bitmap(width - xAdj, height - yAdj); destRect = new System.Drawing.Rectangle(0, 0, width - xAdj, height - yAdj); } // Draw the image onto the new bitmap. System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm); g.DrawImage(imageData, destRect, sourceRect, System.Drawing.GraphicsUnit.Pixel); g.Dispose(); return(bm); } else if (ImageRepeat != Rdl.Engine.BackgroundImage.ImageRepeatEnum.NoRepeat && width > 0 && height > 0) { // If the image is repeated and we know the space that it is going to be repeated into // then draw multiple copies of the image into a new sized bitmap // Create a new bitmap for the image System.Drawing.Bitmap bm = new System.Drawing.Bitmap(width, height);; System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm); System.Drawing.Rectangle sourceRect = System.Drawing.Rectangle.Empty; System.Drawing.Rectangle destRect = System.Drawing.Rectangle.Empty; int x = 0; int y = 0; bool done = false; while (!done) { sourceRect = new System.Drawing.Rectangle(0, 0, Math.Min(imageData.Width, width - x), Math.Min(imageData.Height, height - y)); destRect = new System.Drawing.Rectangle(x, y, Math.Min(imageData.Width, width - x), Math.Min(imageData.Height, height - y)); // Draw the image onto the new bitmap. g.DrawImage(imageData, destRect, sourceRect, System.Drawing.GraphicsUnit.Pixel); if (ImageRepeat == Rdl.Engine.BackgroundImage.ImageRepeatEnum.Repeat || ImageRepeat == Rdl.Engine.BackgroundImage.ImageRepeatEnum.RepeatX) { x += imageData.Width; if (x >= width) { if (ImageRepeat == Rdl.Engine.BackgroundImage.ImageRepeatEnum.Repeat) { x = 0; y += imageData.Height; } else { done = true; } } } if (ImageRepeat == Rdl.Engine.BackgroundImage.ImageRepeatEnum.RepeatY) { y += imageData.Height; } if (y >= height) { done = true; } } g.Dispose(); return(bm); } else { return(imageData); } }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) { //FileUpload fileUpload, //HttpPostedFile hpf = fileUpload.PostedFile; System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); //System.Drawing.Image originalImage = System.Drawing.Image.FromStream(hpf.InputStream, true); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW": //指定高宽缩放(可能变形) break; case "W": //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut": //指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //以jpg格式保存缩略图 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } }
//return "0" for single face and "c"(cache) for multiple face //for multiple face, the face rectangles are stored in CCommon.cacheRects //CComon.cacheBm store the 24bit Bitmap for source image public static string FindFaceAndEyes(BitmapSource srcimage, out System.Drawing.Rectangle facerect, out System.Drawing.Rectangle[] eyesrect) { String faceFileName = AppDomain.CurrentDomain.BaseDirectory + "haarcascade_frontalface_alt2.xml"; String eyeFileName = AppDomain.CurrentDomain.BaseDirectory + "haarcascade_eye.xml"; //working with gdi to get 24bit rgb image System.Drawing.Bitmap bmtest = CCommon.BitmapImage2Bitmap(srcimage); System.Drawing.Bitmap bmsrc24 = new System.Drawing.Bitmap(bmtest.Width, bmtest.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); System.Drawing.Graphics gbmsrc24 = System.Drawing.Graphics.FromImage(bmsrc24); gbmsrc24.DrawImageUnscaled(bmtest, 0, 0); gbmsrc24.Dispose(); bmtest.Dispose(); bmtest = null; if (cacheBm != null) { cacheBm.Dispose(); } cacheBm = (System.Drawing.Bitmap)bmsrc24.Clone(); //we do scaling if the source is too large double scale = 1.0; if (bmsrc24.Height > 500) { scale = (double)500 / bmsrc24.Height; } System.Drawing.Bitmap bm = new System.Drawing.Bitmap((int)(bmsrc24.Width * scale), (int)(bmsrc24.Height * scale), System.Drawing.Imaging.PixelFormat.Format24bppRgb); System.Drawing.Graphics gbm = System.Drawing.Graphics.FromImage(bm); //scale down the source image for face dection gbm.DrawImage(bmsrc24, new System.Drawing.Rectangle(0, 0, bm.Width, bm.Height), new System.Drawing.Rectangle(0, 0, bmsrc24.Width, bmsrc24.Height), System.Drawing.GraphicsUnit.Pixel); gbm.Dispose(); // bm.Save(AppDomain.CurrentDomain.BaseDirectory +"temp\\~bm.jpg",System.Drawing.Imaging.ImageFormat.Jpeg); ////////////////////////////////////////// IntelImage _img = CDetectFace.CreateIntelImageFromBitmap(bm); //IntPtr p_face = CDetectFace.HistEqualize(_img); bm.Dispose(); bm = null; string strindex = ""; using (HaarClassifier haarface = new HaarClassifier(faceFileName)) using (HaarClassifier haareye = new HaarClassifier(eyeFileName)) { var faces = haarface.DetectObjects(_img.IplImage()); // var faces = haarface.DetectObjects(p_face ); if (faces.Count > 0) { List <System.Drawing.Rectangle> facerects = new List <System.Drawing.Rectangle>(); for (int i = 0; i < faces.Count; i++) { var face = faces.ElementAt(i); System.Drawing.Rectangle rt = new System.Drawing.Rectangle((int)(face.x / scale), (int)(face.y / scale), (int)(face.width / scale), (int)(face.height / scale)); facerects.Add(rt); } cacheRects = facerects; if (faces.Count > 1) { //clean up and return eyesrect = null; facerect = facerect = System.Drawing.Rectangle.Empty; _img.Dispose(); bmsrc24.Dispose(); bmsrc24 = null; return("c"); //cached } } else { cacheRects.Clear(); } //only handle 1 face if (faces.Count == 1) { var face = faces.ElementAt(0); facerect = new System.Drawing.Rectangle((int)(face.x / scale), (int)(face.y / scale), (int)(face.width / scale), (int)(face.height / scale)); int x = facerect.X, y = facerect.Y, h0 = facerect.Height, w0 = facerect.Width; //to handle oversize face area double rescale = 1.0; if (h0 > 300) { rescale = 300.0 / h0; } System.Drawing.Rectangle temprect = new System.Drawing.Rectangle(x, y, w0, 10 * h0 / 16); System.Drawing.Bitmap bm_eyes = bmsrc24.cropAtRect(temprect); bm_eyes.Save(AppDomain.CurrentDomain.BaseDirectory + "temp\\~eye.bmp", System.Drawing.Imaging.ImageFormat.Bmp); IntelImage image_eyes = CDetectFace.CreateIntelImageFromBitmap(bm_eyes); //resize eyes area for better detection IntelImage image_eyes2X = new IntelImage((int)(image_eyes.IplImageStruc().width *2 * rescale), (int)(image_eyes.IplImageStruc().height *2 * rescale)); NativeMethods.CvResize(image_eyes.IplImage(), image_eyes2X.IplImage(), NativeMethods.CV_INTER_CUBIC); IntPtr p_eq_img_eyes = CDetectFace.HistEqualize(image_eyes2X); var eyes = haareye.DetectObjects(p_eq_img_eyes); ////clean up NativeMethods.cvReleaseImage(ref p_eq_img_eyes); image_eyes.Dispose(); image_eyes = null; bm_eyes.Dispose(); image_eyes2X.Dispose(); image_eyes2X = null; if (eyes.Count > 0) { eyesrect = new System.Drawing.Rectangle[eyes.Count]; for (int i = 0; i < eyesrect.Length; i++) { var eye = eyes.ElementAt(i); //note that we had scale the eyes area by 2, so we scale back eyesrect[i] = new System.Drawing.Rectangle((int)(eye.x / (2 * rescale)), (int)(eye.y / (2 * rescale)), (int)(eye.width / (2 * rescale)), (int)(eye.height / (2 * rescale))); } int mineyesize = (h0 / 12); int maxeyesize = (h0 / 3); //sorting var tempeyeslist = eyesrect.ToList(); //dist to center of face // <-1/2 w --> // | | | // |<-x ->o<d>| | // | | | // | | | // | | | // o=center of eye // x= x dist to center of eye // d= difference of 1/2 w and x // = distance of eye center to center of face // the further this distance, the more likely it is an eye int half_facewidth = facerect.Width / 2; tempeyeslist = tempeyeslist.OrderByDescending(eye => Math.Abs(eye.X + eye.Width / 2 - (half_facewidth))).ToList(); //size: should be within min and max eye size tempeyeslist = tempeyeslist.OrderByDescending(eye => (eye.Width > mineyesize)).ToList(); tempeyeslist = tempeyeslist.OrderByDescending(eye => (eye.Width < maxeyesize)).ToList(); eyesrect = tempeyeslist.ToArray(); } else { eyesrect = null; } } else { facerect = System.Drawing.Rectangle.Empty; eyesrect = null; } } //NativeMethods.cvReleaseImage(ref p_face ); _img.Dispose(); bmsrc24.Dispose(); bmsrc24 = null; return(strindex); }
/// <summary> /// Draws given bitmap tile to the canvasRenderBitmap /// </summary> /// <param name="position"></param> /// <param name="size"></param> /// <param name="bitmap"></param> private void DrawTile(Point position, int size, System.Drawing.Rectangle bitmap, System.Drawing.Graphics graphics) { System.Drawing.Rectangle positionRectangle = new System.Drawing.Rectangle((int)position.X, (int)position.Y, size, size); graphics.DrawImage(_tilesetHandler.Tileset, positionRectangle, bitmap.X, bitmap.Y, bitmap.Width, bitmap.Height, System.Drawing.GraphicsUnit.Pixel); }
public static System.Drawing.Bitmap CropWhiteSpace(this System.Drawing.Bitmap bmp) { int w = bmp.Width; int h = bmp.Height; Func <int, bool> allWhiteRow = row => { for (int i = 0; i < w; ++i) { if (bmp.GetPixel(i, row).R != 255) { return(false); } } return(true); }; Func <int, bool> allWhiteColumn = col => { for (int i = 0; i < h; ++i) { if (bmp.GetPixel(col, i).R != 255) { return(false); } } return(true); }; int topmost = 0; for (int row = 0; row < h; ++row) { if (allWhiteRow(row)) { topmost = row; } else { break; } } int bottommost = 0; for (int row = h - 1; row >= 0; --row) { if (allWhiteRow(row)) { bottommost = row; } else { break; } } int leftmost = 0, rightmost = 0; for (int col = 0; col < w; ++col) { if (allWhiteColumn(col)) { leftmost = col; } else { break; } } for (int col = w - 1; col >= 0; --col) { if (allWhiteColumn(col)) { rightmost = col; } else { break; } } if (rightmost == 0) { rightmost = w; // As reached left } if (bottommost == 0) { bottommost = h; // As reached top. } int croppedWidth = rightmost - leftmost; int croppedHeight = bottommost - topmost; if (croppedWidth == 0) // No border on left or right { leftmost = 0; croppedWidth = w; } if (croppedHeight == 0) // No border on top or bottom { topmost = 0; croppedHeight = h; } try { var target = new System.Drawing.Bitmap(croppedWidth, croppedHeight); using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(target)) { g.DrawImage(bmp, new System.Drawing.RectangleF(0, 0, croppedWidth, croppedHeight), new System.Drawing.RectangleF(leftmost, topmost, croppedWidth, croppedHeight), System.Drawing.GraphicsUnit.Pixel); } return(target); } catch (Exception ex) { throw new Exception( string.Format("Values are topmost={0} btm={1} left={2} right={3} croppedWidth={4} croppedHeight={5}", topmost, bottommost, leftmost, rightmost, croppedWidth, croppedHeight), ex); } }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) { using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath)) { int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; if (originalImage.Width <= width && originalImage.Height <= height && mode.ToUpper() != "CUT" && mode.ToUpper() != "CUTA") { File.Copy(originalImagePath, thumbnailPath, true); return; } switch (mode.ToUpper()) { case "HW": //指定高宽缩放(可能变形) break; case "W": //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "CUTA": //指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; case "CUT": //指定高宽裁减(不变形)自定义 //if (ow <= towidth && oh <= toheight) //{ // x = -(towidth - ow) / 2; // y = -(toheight - oh) / 2; // ow = towidth; // oh = toheight; //} //else //{ if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } else { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } //if (ow > oh)//宽大于高 //{ // x = 0; // y = -(ow - oh) / 2; // oh = ow; //} //else//高大于宽 //{ // y = 0; // x = -(oh - ow) / 2; // ow = oh; //} //} break; case "CUT1": if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { toheight = originalImage.Height * width / originalImage.Width; } else { towidth = originalImage.Width * height / originalImage.Height; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 //g.Clear(System.Drawing.Color.Transparent); g.Clear(System.Drawing.Color.White); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //string fileExtension = Path.GetExtension(originalImagePath).ToLower(); //switch (fileExtension) //{ // case ".jpg": // //以jpg格式保存缩略图 // bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break; // case ".jpeg": // //以jpg格式保存缩略图 // bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break; // case ".gif": // //以jpg格式保存缩略图 // bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break; // case ".png": // bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break; //} //以jpg格式保存缩略图 //bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); ImageCodecInfo ici; System.Drawing.Imaging.Encoder enc; EncoderParameter ep; EncoderParameters epa; // Initialize the necessary objects ici = GetEncoderInfo("image/jpeg"); enc = System.Drawing.Imaging.Encoder.Quality;//设置保存质量 epa = new EncoderParameters(1); // Set the compression level ep = new EncoderParameter(enc, 90L);//质量等级为90% epa.Param[0] = ep; bitmap.Save(thumbnailPath, ici, epa); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } } }
public void Update(PlatformGameLifecycleDTO CurrentGame) { Game = CurrentGame; BlueBansLabel.Visibility = System.Windows.Visibility.Hidden; PurpleBansLabel.Visibility = System.Windows.Visibility.Hidden; PurpleBanListView.Items.Clear(); BlueBanListView.Items.Clear(); BlueListView.Items.Clear(); PurpleListView.Items.Clear(); ImageGrid.Children.Clear(); List <Participant> AllParticipants = new List <Participant>(CurrentGame.Game.TeamOne.ToArray()); AllParticipants.AddRange(CurrentGame.Game.TeamTwo); int i = 0; int y = 0; foreach (Participant part in AllParticipants) { ChampSelectPlayer control = new ChampSelectPlayer(); if (part is PlayerParticipant) { PlayerParticipant participant = part as PlayerParticipant; foreach (PlayerChampionSelectionDTO championSelect in CurrentGame.Game.PlayerChampionSelections) { if (championSelect.SummonerInternalName == participant.SummonerInternalName) { control.ChampionImage.Source = champions.GetChampion(championSelect.ChampionId).icon; var uriSource = new Uri(Path.Combine(Client.ExecutingDirectory, "Assets", "spell", SummonerSpell.GetSpellImageName(Convert.ToInt32(championSelect.Spell1Id))), UriKind.Absolute); control.SummonerSpell1.Source = new BitmapImage(uriSource); uriSource = new Uri(Path.Combine(Client.ExecutingDirectory, "Assets", "spell", SummonerSpell.GetSpellImageName(Convert.ToInt32(championSelect.Spell2Id))), UriKind.Absolute); control.SummonerSpell2.Source = new BitmapImage(uriSource); #region Generate Background Image m = new Image(); Canvas.SetZIndex(m, -2); m.Stretch = Stretch.None; m.Width = 100; m.Opacity = 0.50; m.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; m.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; m.Margin = new System.Windows.Thickness(y++ *100, 0, 0, 0); System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle(new System.Drawing.Point(100, 0), new System.Drawing.Size(100, 560)); System.Drawing.Bitmap src = System.Drawing.Image.FromFile(Path.Combine(Client.ExecutingDirectory, "Assets", "champions", champions.GetChampion(championSelect.ChampionId).portraitPath)) as System.Drawing.Bitmap; System.Drawing.Bitmap target = new System.Drawing.Bitmap(cropRect.Width, cropRect.Height); using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(target)) { g.DrawImage(src, new System.Drawing.Rectangle(0, 0, target.Width, target.Height), cropRect, System.Drawing.GraphicsUnit.Pixel); } m.Source = Client.ToWpfBitmap(target); ImageGrid.Children.Add(m); #endregion Generate Background } } control.PlayerName.Content = participant.SummonerName; if (participant.TeamParticipantId != null) { byte[] values = BitConverter.GetBytes((double)participant.TeamParticipantId); if (!BitConverter.IsLittleEndian) { Array.Reverse(values); } byte r = values[2]; byte b = values[3]; byte g = values[4]; System.Drawing.Color myColor = System.Drawing.Color.FromArgb(r, b, g); var converter = new System.Windows.Media.BrushConverter(); var brush = (Brush)converter.ConvertFromString("#" + myColor.Name); control.TeamRectangle.Fill = brush; control.TeamRectangle.Visibility = System.Windows.Visibility.Visible; } } i++; if (i <= 5) { BlueListView.Items.Add(control); } else { PurpleListView.Items.Add(control); } } if (CurrentGame.Game.BannedChampions.Count > 0) { BlueBansLabel.Visibility = System.Windows.Visibility.Visible; PurpleBansLabel.Visibility = System.Windows.Visibility.Visible; } foreach (var x in CurrentGame.Game.BannedChampions) { Image champImage = new Image(); champImage.Height = 58; champImage.Width = 58; champImage.Source = champions.GetChampion(x.ChampionId).icon; if (x.TeamId == 100) { BlueBanListView.Items.Add(champImage); } else { PurpleBanListView.Items.Add(champImage); } } try { string mmrJSON = ""; string url = Client.Region.SpectatorLink + "consumer/getGameMetaData/" + Client.Region.InternalName + "/" + CurrentGame.Game.Id + "/token"; using (WebClient client = new WebClient()) { mmrJSON = client.DownloadString(url); } JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary <string, object> deserializedJSON = serializer.Deserialize <Dictionary <string, object> >(mmrJSON); MMRLabel.Content = "≈" + deserializedJSON["interestScore"]; } catch { MMRLabel.Content = "N/A"; } }
/// <summary> /// /// </summary> /// <param name="minimapFrameProperty">UI.wz/UIWindow2.img/MiniMap</param> /// <param name="mapBoard"></param> /// <param name="device"></param> /// <param name="MapName">The map name. i.e The Hill North</param> /// <param name="StreetName">The street name. i.e Hidden street</param> /// <returns></returns> public static MinimapItem CreateMinimapFromProperty(WzSubProperty minimapFrameProperty, Board mapBoard, GraphicsDevice device, string MapName, string StreetName) { WzSubProperty maxMapProperty = (WzSubProperty)minimapFrameProperty["MaxMap"]; WzSubProperty miniMapProperty = (WzSubProperty)minimapFrameProperty["MinMap"]; WzSubProperty maxMapMirrorProperty = (WzSubProperty)minimapFrameProperty["MaxMapMirror"]; // for Zero maps WzSubProperty miniMapMirrorProperty = (WzSubProperty)minimapFrameProperty["MinMapMirror"]; // for Zero maps WzSubProperty useFrame; if (mapBoard.MapInfo.zeroSideOnly || MapConstants.IsZerosTemple(mapBoard.MapInfo.id)) // zero's temple { useFrame = maxMapMirrorProperty; } else { useFrame = maxMapProperty; } // Wz frames System.Drawing.Bitmap c = ((WzCanvasProperty)useFrame?["c"])?.GetLinkedWzCanvasBitmap(); System.Drawing.Bitmap e = ((WzCanvasProperty)useFrame?["e"])?.GetLinkedWzCanvasBitmap(); System.Drawing.Bitmap n = ((WzCanvasProperty)useFrame?["n"])?.GetLinkedWzCanvasBitmap(); System.Drawing.Bitmap s = ((WzCanvasProperty)useFrame?["s"])?.GetLinkedWzCanvasBitmap(); System.Drawing.Bitmap w = ((WzCanvasProperty)useFrame?["w"])?.GetLinkedWzCanvasBitmap(); System.Drawing.Bitmap ne = ((WzCanvasProperty)useFrame?["ne"])?.GetLinkedWzCanvasBitmap(); // top right System.Drawing.Bitmap nw = ((WzCanvasProperty)useFrame?["nw"])?.GetLinkedWzCanvasBitmap(); // top left System.Drawing.Bitmap se = ((WzCanvasProperty)useFrame?["se"])?.GetLinkedWzCanvasBitmap(); // bottom right System.Drawing.Bitmap sw = ((WzCanvasProperty)useFrame?["sw"])?.GetLinkedWzCanvasBitmap(); // bottom left // Constants const float TOOLTIP_FONTSIZE = 10f; System.Drawing.Color color_bgFill = System.Drawing.Color.Transparent; System.Drawing.Color color_foreGround = System.Drawing.Color.White; string renderText = string.Format("{0}{1}{2}", StreetName, Environment.NewLine, MapName); // Map background image System.Drawing.Bitmap miniMapImage = mapBoard.MiniMap; // the original minimap image without UI frame overlay int effective_width = miniMapImage.Width + e.Width + w.Width; int effective_height = miniMapImage.Height + n.Height + s.Height; using (System.Drawing.Font font = new System.Drawing.Font(GLOBAL_FONT, TOOLTIP_FONTSIZE)) { // Get the width of the 'streetName' or 'mapName' System.Drawing.Graphics graphics_dummy = System.Drawing.Graphics.FromImage(new System.Drawing.Bitmap(1, 1)); // dummy image just to get the Graphics object for measuring string System.Drawing.SizeF tooltipSize = graphics_dummy.MeasureString(renderText, font); effective_width = Math.Max((int)tooltipSize.Width + nw.Width, effective_width); // set new width System.Drawing.Bitmap miniMapUIImage = new System.Drawing.Bitmap(effective_width, effective_height); int mapDrawPositionX = (effective_width / 2) - nw.Width; // map is on the center. The position relative to the UI using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(miniMapUIImage)) { // Frames and background UIFrameHelper.DrawUIFrame(graphics, color_bgFill, ne, nw, se, sw, e, w, n, s, null, effective_width, effective_height); graphics.DrawString( renderText, font, new System.Drawing.SolidBrush(color_foreGround), 50, 20); // Map mark if (Program.InfoManager.MapMarks.ContainsKey(mapBoard.MapInfo.mapMark)) { System.Drawing.Bitmap mapMark = Program.InfoManager.MapMarks[mapBoard.MapInfo.mapMark]; graphics.DrawImage(mapMark.ToImage(), 7, 17); } // Map image graphics.DrawImage(miniMapImage, mapDrawPositionX, // map is on the center n.Height); graphics.Flush(); } // Dots pixel System.Drawing.Bitmap bmp_DotPixel = new System.Drawing.Bitmap(2, 4); using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bmp_DotPixel)) { graphics.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Yellow), new System.Drawing.RectangleF(0, 0, bmp_DotPixel.Width, bmp_DotPixel.Height)); graphics.Flush(); } IDXObject dxObj_miniMapPixel = new DXObject(0, n.Height, bmp_DotPixel.ToTexture2D(device), 0); BaseDXDrawableItem item_pixelDot = new BaseDXDrawableItem(dxObj_miniMapPixel, false) { Position = new Point( mapDrawPositionX, // map is on the center 0) }; // Map Texture2D texturer_miniMap = miniMapUIImage.ToTexture2D(device); IDXObject dxObj = new DXObject(0, 0, texturer_miniMap, 0); MinimapItem item = new MinimapItem(dxObj, item_pixelDot); return(item); } }
protected void Page_Load(object sender, EventArgs e) { // System.Drawing.Image thumbnail_image = null;//缩略图 System.Drawing.Image original_image = null; //原图 System.Drawing.Bitmap final_image = null; //最终图片 System.Drawing.Graphics graphic = null; MemoryStream ms = null; try { // Get the data HttpPostedFile jpeg_image_upload = Request.Files["Filedata"]; // Retrieve the uploaded image original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream); int width = original_image.Width; int height = original_image.Height; final_image = new System.Drawing.Bitmap(original_image); graphic = System.Drawing.Graphics.FromImage(final_image); graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphic.DrawImage(original_image, 0, 0, width, height); ms = new MemoryStream(); final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer()); List <Thumbnail> thumbnails = Session["file_info"] as List <Thumbnail>; if (thumbnails == null) { thumbnails = new List <Thumbnail>(); Session["file_info"] = thumbnails; } thumbnails.Add(thumb); Response.StatusCode = 200; Response.Write(thumbnail_id); } catch (Exception ex) { Response.StatusCode = 500; Response.Write("An error occured"); Response.End(); } finally { // Clean up if (final_image != null) { final_image.Dispose(); } if (graphic != null) { graphic.Dispose(); } if (ms != null) { ms.Close(); } Response.End(); } }
/// <summary> /// 加图片水印 /// </summary> /// <param name="filename">文件名</param> /// <param name="watermarkFilename">水印文件名</param> /// <param name="watermarkStatus">图片水印位置:0=不使用 1=左上 2=中上 3=右上 4=左中 ... 9=右下</param> /// <param name="quality">是否是高质量图片 取值范围0--100</param> /// <param name="watermarkTransparency">图片水印透明度 取值范围1--10 (10为不透明)</param> public static void AddImageSignPic(string Path, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { System.Drawing.Image img = System.Drawing.Image.FromFile(Path); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(img); //设置高质量插值法 //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; System.Drawing.Image watermark = new System.Drawing.Bitmap(watermarkFilename); if (watermark.Height >= img.Height || watermark.Width >= img.Width) { return; } System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes(); System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap(); colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0); System.Drawing.Imaging.ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap); float transparency = 0.5F; if (watermarkTransparency >= 1 && watermarkTransparency <= 10) { transparency = (watermarkTransparency / 10.0F); } float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap); int xpos = 0; int ypos = 0; switch (watermarkStatus) { case 1: xpos = (int)(img.Width * (float).01); ypos = (int)(img.Height * (float).01); break; case 2: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)(img.Height * (float).01); break; case 3: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)(img.Height * (float).01); break; case 4: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 5: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 6: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 7: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 8: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 9: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; } g.DrawImage(watermark, new System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes); System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo ici = null; foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs) { //if (codec.MimeType.IndexOf("jpeg") > -1) if (codec.MimeType.Contains("jpeg")) { ici = codec; } } System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) { img.Save(filename, ici, encoderParams); } else { img.Save(filename); } g.Dispose(); img.Dispose(); watermark.Dispose(); imageAttributes.Dispose(); }
public static System.Drawing.Bitmap CropImage(System.Drawing.Image Image, int Width, int Height) { if ((Image != null)) { if (Image.Width > Width || Image.Height > Height) { decimal Ratio = Convert.ToDecimal(Image.Width) / Convert.ToDecimal(Image.Height); int SizedWidth = Image.Width; int SizedHeight = Image.Height; if (Ratio > 1) { if (Height > Image.Height) { Height = Image.Height; } SizedHeight = Height; SizedWidth = Convert.ToInt32(SizedHeight * Ratio); } else { if (Width > Image.Width) { Width = Image.Width; } SizedWidth = Width; SizedHeight = Convert.ToInt32(SizedWidth / Ratio); } System.Drawing.Bitmap NewImage = null; if (Image.PixelFormat.ToString().Contains("Indexed")) { NewImage = new System.Drawing.Bitmap(Convert.ToInt32(SizedWidth), Convert.ToInt32(SizedHeight)); } else { NewImage = new System.Drawing.Bitmap(SizedWidth, SizedHeight, Image.PixelFormat); } System.Drawing.Graphics Graph = System.Drawing.Graphics.FromImage(NewImage); Graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; Graph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; Graph.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; Graph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; System.Drawing.Rectangle Rect = new System.Drawing.Rectangle(0, 0, SizedWidth, SizedHeight); Graph.DrawImage(Image, Rect); System.Drawing.Rectangle CroppedRect = new System.Drawing.Rectangle((NewImage.Width - Width) / 2, (NewImage.Height - Height) / 2, Width, Height); System.Drawing.Bitmap BMP = NewImage.Clone(CroppedRect, NewImage.PixelFormat); return(BMP); } else { System.Drawing.Bitmap NewImage = null; if (Image.PixelFormat.ToString().Contains("Indexed")) { NewImage = new System.Drawing.Bitmap(Convert.ToInt32(Image.Width), Convert.ToInt32(Image.Height)); } else { NewImage = new System.Drawing.Bitmap(Image.Width, Image.Height, Image.PixelFormat); } System.Drawing.Graphics Graph = System.Drawing.Graphics.FromImage(NewImage); Graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; Graph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; Graph.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; Graph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; System.Drawing.Rectangle Rect = new System.Drawing.Rectangle(0, 0, Image.Width, Image.Height); Graph.DrawImage(Image, Rect); return(NewImage); } } return(null); }
public string CombineBitmap_WatermarkImage(string WorkingDirectory, string FirstImageName, string SecondImagePath) { string FirstImagePath = System.IO.Path.Combine(WorkingDirectory, FirstImageName); string FinalImageName = Guid.NewGuid().ToString() + ".png"; //read all images into memory System.Drawing.Bitmap finalImage = null; System.Drawing.Bitmap First_Image = null; System.Drawing.Bitmap Second_Image = null; try { int width = 0; int height = 0; First_Image = new System.Drawing.Bitmap(FirstImagePath); Second_Image = new System.Drawing.Bitmap(SecondImagePath); width = First_Image.Width; height = First_Image.Height + Second_Image.Height; //create a bitmap to hold the combined image finalImage = new System.Drawing.Bitmap(width, height); //get a graphics object from the image so we can draw on it using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage)) { //set background color g.Clear(System.Drawing.Color.Black); //go through each image and draw it on the final image int offset = 0; g.DrawImage(First_Image, new System.Drawing.Rectangle(0, 0, First_Image.Width, First_Image.Height)); g.DrawImage(Second_Image, new System.Drawing.Rectangle(First_Image.Width - Second_Image.Width, First_Image.Height, Second_Image.Width, Second_Image.Height)); } finalImage.Save(WorkingDirectory + "\\" + FinalImageName, ImageFormat.Png); // imgPhoto.Dispose(); finalImage.Dispose(); return(FinalImageName); } catch (Exception ex) { ErrorHandling.HandleException(ex); if (finalImage != null) { finalImage.Dispose(); } //throw ex; throw ex; } finally { //clean up memory First_Image.Dispose(); Second_Image.Dispose(); } }
private string CreateImage() { string thumbnail_id = string.Empty; System.Drawing.Image thumbnail_image = null; System.Drawing.Image original_image = null; System.Drawing.Bitmap final_image = null; System.Drawing.Graphics graphic = null; MemoryStream ms = null; try { HttpPostedFile jpeg_image_upload = Request.Files["Filedata"]; original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream); int new_width = original_image.Width; int new_height = original_image.Height; int target_width = new_width; int target_height = new_height; final_image = new System.Drawing.Bitmap(target_width, target_height); graphic = System.Drawing.Graphics.FromImage(final_image); graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height)); int paste_x = (target_width - new_width) / 2; int paste_y = (target_height - new_height) / 2; graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */ graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height); ms = new MemoryStream(); final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer()); List <Thumbnail> thumbnails = Session["file_info"] as List <Thumbnail>; if (thumbnails == null) { thumbnails = new List <Thumbnail>(); HttpContext.Current.Session["file_info"] = thumbnails; } thumbnails.Add(thumb); } catch { return(string.Empty); } finally { // Clean up if (final_image != null) { final_image.Dispose(); } if (graphic != null) { graphic.Dispose(); } if (original_image != null) { original_image.Dispose(); } if (thumbnail_image != null) { thumbnail_image.Dispose(); } if (ms != null) { ms.Close(); } } return(thumbnail_id); }
/// <summary> /// Draws the control. /// </summary> /// <param name="g"></param> private void Draw(Graphics g) { Brush bgBrush = new HatchBrush(HatchStyle.DarkDownwardDiagonal, Color.Gray, Color.LightGray); g.FillRectangle(bgBrush, 0, 0, THUMB_WIDTH, THUMB_HEIGHT); g.DrawImage(thumb, 0, 0); g.DrawString(Label, ElementFont, new System.Drawing.SolidBrush(ForeColor), THUMB_WIDTH + 5, 10); }
/// <summary> /// 生成二维码 /// </summary> /// <param name="Content">内容文本</param> /// <param name="QRCodeEncodeMode">二维码编码方式</param> /// <param name="QRCodeErrorCorrect">纠错码等级</param> /// <param name="QRCodeVersion">二维码版本号 0-40</param> /// <param name="QRCodeScale">每个小方格的预设宽度(像素),正整数</param> /// <param name="size">图片尺寸(像素),0表示不设置</param> /// <param name="border">图片白边(像素),当size大于0时有效</param> /// <returns></returns> public System.Drawing.Image CreateQRCode(string Content, QRCodeEncoder.ENCODE_MODE QRCodeEncodeMode, QRCodeEncoder.ERROR_CORRECTION QRCodeErrorCorrect, int QRCodeVersion, int QRCodeScale, int size, int border) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncodeMode; qrCodeEncoder.QRCodeErrorCorrect = QRCodeErrorCorrect; qrCodeEncoder.QRCodeScale = QRCodeScale; qrCodeEncoder.QRCodeVersion = QRCodeVersion; System.Drawing.Image image = qrCodeEncoder.Encode(Content); #region 根据设定的目标图片尺寸调整二维码QRCodeScale设置,并添加边框 if (size > 0) { //当设定目标图片尺寸大于生成的尺寸时,逐步增大方格尺寸 #region 当设定目标图片尺寸大于生成的尺寸时,逐步增大方格尺寸 while (image.Width < size) { qrCodeEncoder.QRCodeScale++; System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content); if (imageNew.Width < size) { image = new System.Drawing.Bitmap(imageNew); imageNew.Dispose(); imageNew = null; } else { qrCodeEncoder.QRCodeScale--; //新尺寸未采用,恢复最终使用的尺寸 imageNew.Dispose(); imageNew = null; break; } } #endregion //当设定目标图片尺寸小于生成的尺寸时,逐步减小方格尺寸 #region 当设定目标图片尺寸小于生成的尺寸时,逐步减小方格尺寸 while (image.Width > size && qrCodeEncoder.QRCodeScale > 1) { qrCodeEncoder.QRCodeScale--; System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content); image = new System.Drawing.Bitmap(imageNew); imageNew.Dispose(); imageNew = null; if (image.Width < size) { break; } } #endregion //如果目标尺寸大于生成的图片尺寸,则为图片增加白边 #region 如果目标尺寸大于生成的图片尺寸,则为图片增加白边 if (image.Width <= size) { //根据参数设置二维码图片白边的最小宽度 #region 根据参数设置二维码图片白边的最小宽度 if (border > 0) { while (image.Width <= size && size - image.Width < border * 2 && qrCodeEncoder.QRCodeScale > 1) { qrCodeEncoder.QRCodeScale--; System.Drawing.Image imageNew = qrCodeEncoder.Encode(Content); image = new System.Drawing.Bitmap(imageNew); imageNew.Dispose(); imageNew = null; } } #endregion //当目标图片尺寸大于二维码尺寸时,将二维码绘制在目标尺寸白色画布的中心位置 if (image.Width < size) { //新建空白绘图 System.Drawing.Bitmap panel = new System.Drawing.Bitmap(size, size); System.Drawing.Graphics graphic0 = System.Drawing.Graphics.FromImage(panel); int p_left = 0; int p_top = 0; if (image.Width <= size) //如果原图比目标形状宽 { p_left = (size - image.Width) / 2; } if (image.Height <= size) { p_top = (size - image.Height) / 2; } //将生成的二维码图像粘贴至绘图的中心位置 graphic0.DrawImage(image, p_left, p_top, image.Width, image.Height); image = new System.Drawing.Bitmap(panel); panel.Dispose(); panel = null; graphic0.Dispose(); graphic0 = null; } } #endregion } #endregion return(image); }
private void ParseSpectatorGames() { if (gameList == null) { return; } if (gameList.Count <= 0) { return; } BlueBansLabel.Visibility = Visibility.Hidden; PurpleBansLabel.Visibility = Visibility.Hidden; BlueBanListView.Items.Clear(); PurpleBanListView.Items.Clear(); BlueListView.Items.Clear(); PurpleListView.Items.Clear(); int GameId = 0; var objectGame = gameList[SelectedGame]; Dictionary <string, object> SpectatorGame = objectGame as Dictionary <string, object>; ImageGrid.Children.Clear(); foreach (KeyValuePair <string, object> pair in SpectatorGame) { if (pair.Key == "participants") { ArrayList players = pair.Value as ArrayList; int i = 0; foreach (var objectPlayer in players) { Dictionary <string, object> playerInfo = objectPlayer as Dictionary <string, object>; int teamId = 100; int championId = 0; int spell1Id = 0; int spell2Id = 0; string PlayerName = ""; foreach (KeyValuePair <string, object> playerPair in playerInfo) { if (playerPair.Key == "teamId") { teamId = (int)playerPair.Value; } if (playerPair.Key == "championId") { championId = (int)playerPair.Value; } if (playerPair.Key == "summonerName") { PlayerName = playerPair.Value as string; } if (playerPair.Key == "spell1Id") { spell1Id = (int)playerPair.Value; } if (playerPair.Key == "spell2Id") { spell2Id = (int)playerPair.Value; } } ChampSelectPlayer control = new ChampSelectPlayer(); control.ChampionImage.Source = champions.GetChampion(championId).icon; var uriSource = new Uri(Path.Combine(Client.ExecutingDirectory, "Assets", "spell", SummonerSpell.GetSpellImageName(spell1Id)), UriKind.Absolute); control.SummonerSpell1.Source = new BitmapImage(uriSource); uriSource = new Uri(Path.Combine(Client.ExecutingDirectory, "Assets", "spell", SummonerSpell.GetSpellImageName(spell2Id)), UriKind.Absolute); control.SummonerSpell2.Source = new BitmapImage(uriSource); control.PlayerName.Content = PlayerName; Image m = new Image(); Canvas.SetZIndex(m, -2); //Put background behind everything m.Stretch = Stretch.None; m.Width = 100; m.Opacity = 0.30; m.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; m.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; m.Margin = new System.Windows.Thickness(i++ *100, 0, 0, 0); System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle(new System.Drawing.Point(100, 0), new System.Drawing.Size(100, 560)); System.Drawing.Bitmap src = System.Drawing.Image.FromFile(Path.Combine(Client.ExecutingDirectory, "Assets", "champions", champions.GetChampion(championId).portraitPath)) as System.Drawing.Bitmap; System.Drawing.Bitmap target = new System.Drawing.Bitmap(cropRect.Width, cropRect.Height); using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(target)) { g.DrawImage(src, new System.Drawing.Rectangle(0, 0, target.Width, target.Height), cropRect, System.Drawing.GraphicsUnit.Pixel); } m.Source = Client.ToWpfBitmap(target); ImageGrid.Children.Add(m); if (teamId == 100) { BlueListView.Items.Add(control); } else { PurpleListView.Items.Add(control); } } } else if (pair.Key == "gameId") { GameId = (int)pair.Value; } else if (pair.Key == "mapId") { MapLabel.Content = BaseMap.GetMap((int)pair.Value).DisplayName; } else if (pair.Key == "gameLength") { var seconds = (int)pair.Value; GameTimeLabel.Content = string.Format("{0:D}:{1:00} min", seconds / 60, seconds % 60); } else if (pair.Key == "bannedChampions") { //ArrayList players = pair.Value as ArrayList; //Dictionary<string, object> playerInfo = objectPlayer as Dictionary<string, object>; //foreach (KeyValuePair<string, object> playerPair in playerInfo) ArrayList keyArray = pair.Value as ArrayList; if (keyArray.Count > 0) { BlueBansLabel.Visibility = Visibility.Visible; PurpleBansLabel.Visibility = Visibility.Visible; } foreach (Dictionary <string, object> keyArrayP in keyArray) //Dictionary<string, object> keyArrayP = keyArray as Dictionary<string, object>; { int cid = 0; int teamId = 100; foreach (KeyValuePair <string, object> keyArrayPair in keyArrayP) { if (keyArrayPair.Key == "championId") { cid = (int)keyArrayPair.Value; } if (keyArrayPair.Key == "teamId") { teamId = (int)keyArrayPair.Value; } } ListViewItem item = new ListViewItem(); Image champImage = new Image(); champImage.Height = 58; champImage.Width = 58; //temp try { champImage.Source = champions.GetChampion(cid).icon; } catch { } item.Content = champImage; if (teamId == 100) { BlueBanListView.Items.Add(item); } else { PurpleBanListView.Items.Add(item); } } } } try { BaseRegion region = BaseRegion.GetRegion((string)SpectatorComboBox.SelectedValue); string spectatorJSON = ""; string url = region.SpectatorLink + "consumer/getGameMetaData/" + region.InternalName + "/" + GameId + "/token"; using (WebClient client = new WebClient()) { spectatorJSON = client.DownloadString(url); } JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary <string, object> deserializedJSON = serializer.Deserialize <Dictionary <string, object> >(spectatorJSON); MMRLabel.Content = "≈" + deserializedJSON["interestScore"]; } catch { MMRLabel.Content = "N/A"; } }
/// <summary> /// Resizes an image (down) or returns the original if no resize is needed. /// </summary> /// <param name="contents">The image stream to resize.</param> /// <param name="size">The desired size of the image (highest value between height and width).</param> /// <param name="resizefactor">The factor to use for sizing down the image. Only used if size is 0.</param> /// <param name="quality">The quality of the resized image, between 1 and 100.</param> /// <returns></returns> public static Stream ResizeImage(Stream contents, int size, decimal resizefactor, long quality) { Stream output; if (resizefactor <= 0 || resizefactor > 100) { resizefactor = 100; } decimal coefficient = resizefactor / 100; if (size <= 0 && (coefficient > 1 || coefficient < 0)) // cannot scale up or to a negative value, return original { return(contents); } using (System.Drawing.Image original = System.Drawing.Image.FromStream(contents)) { //calculate new width and height based on size or coefficient int width, height; if (original.Height > original.Width) { if (size <= 0) { size = (int)(original.Height * coefficient); } height = size; width = (int)(original.Width * ((float)size / (float)original.Height)); } else { if (size <= 0) { size = (int)(original.Width * coefficient); } width = size; height = (int)(original.Height * ((float)size / (float)original.Width)); } using (System.Drawing.Bitmap resized = new System.Drawing.Bitmap(width, height, original.PixelFormat)) { resized.SetResolution(original.HorizontalResolution, original.VerticalResolution); using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(resized)) { graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.DrawImage(original, new System.Drawing.Rectangle(0, 0, width, height), 0, 0, original.Width, original.Height, System.Drawing.GraphicsUnit.Pixel); } #region codec info //if (contentType == "image/gif") //{ // using (thumbnail) // { // OctreeQuantizer quantizer = new OctreeQuantizer(255, 8); // using (Bitmap quantized = quantizer.Quantize(bitmap)) // { // Response.ContentType = "image/gif"; // quantized.Save(Response.OutputStream, ImageFormat.Gif); // } // } //} //if (contentType == "image/jpeg") //{ // var info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); // EncoderParameters encoderParameters; // encoderParameters = new EncoderParameters(1); // encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); // Response.ContentType = "image/jpeg"; // thumbnail.Save(Response.OutputStream, info[1], encoderParameters); //} #endregion //encode the image ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg); Encoder myEncoder = Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality); myEncoderParameters.Param[0] = myEncoderParameter; //save it to server output = new MemoryStream(); resized.Save(output, jgpEncoder, myEncoderParameters); } } return(output); }