public void GetIconHandleTest() { // Verify the kind of exception when the ImageList is empty. ImageHandler handler = new ImageHandler(); Assert.IsTrue(Utilities.HasFunctionThrown<InvalidOperationException>(delegate { handler.GetIconHandle(0); })); try { // Set the image list property so that the object is no more empty. handler.ImageList = Microsoft.VisualStudio.Shell.PackageUtilities.GetImageList(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); Assert.IsNotNull(handler.ImageList); // Verify the kind of exception in case of a bad index. Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentOutOfRangeException>(delegate { handler.GetIconHandle(-1); })); Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentOutOfRangeException>(delegate { handler.GetIconHandle(handler.ImageList.Images.Count); })); // Get the handle for one of the images IntPtr iconHandle = handler.GetIconHandle(1); Assert.AreNotEqual<IntPtr>(IntPtr.Zero, iconHandle); // Verify the image. Icon icon = Icon.FromHandle(iconHandle); Bitmap resultBmp = icon.ToBitmap(); Bitmap expectedBmp = handler.ImageList.Images[1] as Bitmap; // The bitmaps should match. VerifySameBitmap(expectedBmp, resultBmp); } finally { handler.Close(); } }
// Use this for initialization void Start() { escena = Strings.getTextoEscena (sceneNumber); text = this.GetComponent<Text> (); image = GameObject.Find ("Image").GetComponent<ImageHandler> (); if (autoMatic) { StartCoroutine("nextMatic"); } }
public LeftPanel() { // A warning was causing some delay, the warning was not important. Surpressing it. #if DEBUG System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level = System.Diagnostics.SourceLevels.Critical; #endif InitializeComponent(); _imgHandler = new ImageHandler(); _imgHandler.LoadImages(); }
public async Task image_handler_rest_api_test(string url) { var handler = new ImageHandler("api", new MemoryImageCache(), new LocalImageLoader()) { InnerHandler = new HttpClientHandler() }; var client = new HttpClient(handler) { BaseAddress = new Uri("http://localhost/api/local/") }; var response = await client.GetAsync(url); var content = await response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync(); var image = Image.Load(content); image.VerifyAndSave($"TestResult/Http/{ Uri.EscapeDataString(url) }.png"); }
public Layer() { Image = new ImageHandler(); underlayTiles = new List<Tile>(); overlayTiles = new List<Tile>(); SolidTiles = String.Empty; OverlayTiles = String.Empty; PortalTiles = String.Empty; NextScreen = String.Empty; LadderTiles = String.Empty; InteractionTiles = String.Empty; }
/// <summary> /// Play a video into a window using the GenericSampleSourceFilter as the video source /// </summary> /// <param name="sPath">Path for the ImageFromFiles class (if that's what we are using) /// to use to find images</param> /// <param name="hWin">Window to play the video in</param> public DxPlay(string sPath, Control hWin) { try { // pick one of our image providers //m_ImageHandler = new ImageFromFiles(sPath, 8); m_ImageHandler = new ImageFromPixels(20); //m_ImageHandler = new ImageFromMpg(@"c:\c1.mpg"); //m_ImageHandler = new ImageFromMP3(@"c:\vss\media\track3.mp3"); // Set up the graph SetupGraph(hWin); } catch { Dispose(); throw; } }
public void AddImageTest() { Bitmap newBmp = new Bitmap(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.Image1.bmp")); // Case 1: Add an image to an empty ImageHandler. ImageHandler handler = new ImageHandler(); try { Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentNullException>(delegate { handler.AddImage(null); })); handler.AddImage(newBmp); Assert.IsNotNull(handler.ImageList); Assert.AreEqual(1, handler.ImageList.Images.Count); } finally { handler.Close(); } // Case 2: Add a new image to a not empty image handler handler = new ImageHandler(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); try { Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentNullException>(delegate { handler.AddImage(null); })); handler.AddImage(newBmp); Assert.IsNotNull(handler.ImageList); Assert.AreEqual(4, handler.ImageList.Images.Count); // Verify that it is possible to get the icon handle for the // last (new) element in the list. IntPtr iconHandle = handler.GetIconHandle(3); Assert.AreNotEqual<IntPtr>(IntPtr.Zero, iconHandle); // Verify the image. Icon icon = Icon.FromHandle(iconHandle); Bitmap resultBmp = icon.ToBitmap(); Bitmap expectedBmp = handler.ImageList.Images[3] as Bitmap; VerifySameBitmap(expectedBmp, resultBmp); } finally { handler.Close(); } }
public void ImageHandlerConstructors() { // Default constructor. ImageHandler handler = new ImageHandler(); Assert.IsNull(handler.ImageList); // Constructor from resource stream. System.IO.Stream nullStream = null; Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentNullException>(delegate { new ImageHandler(nullStream); })); try { handler = new ImageHandler(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); Assert.IsNotNull(handler.ImageList); Assert.AreEqual<int>(3, handler.ImageList.Images.Count); } finally { handler.Close(); handler = null; } ImageList imageList = null; Assert.IsTrue(Utilities.HasFunctionThrown<ArgumentNullException>(delegate { new ImageHandler(imageList); })); imageList = Microsoft.VisualStudio.Shell.PackageUtilities.GetImageList(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); Assert.IsNotNull(imageList); try { handler = new ImageHandler(imageList); Assert.IsNotNull(handler.ImageList); Assert.AreEqual<ImageList>(imageList, handler.ImageList); } finally { handler.Close(); handler = null; } }
protected BitmapCropAndHandleStrategy(ImageHandler performer) { this.performer = performer; }
public static IList<SearchService.MutualFriendsClass> GetMutualFriendsList(string viewer, string viewed, ImageHandler.eFacebookImageType fbImageSize) { if (HttpContext.Current.Session == null) { } var dic = (Dictionary<string, List<string>>)Global.GetSessionState()["MatchmakingRequestedDic"]; if (dic == null) { } if (!dic.ContainsKey(viewed)) dic.Add(viewed, new List<string>()); var reqList = (List<string>)dic[viewed]; DateTime[] t = new DateTime[5]; t[0] = DateTime.Now; var searchAppMF = new MutualFriendsSearch { Viewer = viewer, Viewed = viewed }; var searchAppResults = searchAppMF.GetResults(); User[] appMF = (searchAppResults != null) ? searchAppResults.Get() : new User[] { }; t[1] = DateTime.Now; IList<SearchService.MutualFriendsClass> mfList = null; //using (var db = new ezFixUpDataContext()) { mfList = appMF.Select(user => new SearchService.MutualFriendsClass { Name = UserSession.GetViewedUserDisplayedNameByUsername(viewer, user.Username), Username = user.Username, PhotoId = Photo.GetPrimaryOrDefaultId(user.Username), PhotoUrl = Photo.GetPrimaryOrDefaultId(user.Username) == 0 && user.FacebookID.HasValue ? ImageHandler.CreateFacebookImageUrl(user.FacebookID.Value,ImageHandler.eFacebookImageType.Square) : ImageHandler.CreateImageUrl(Photo.GetPrimaryOrDefaultId(user.Username), 50, 50, false, true, true), AlreadyRequested = reqList.Contains(user.Username) }).ToList(); } t[2] = DateTime.Now; if (FacebookHelper.IsCurrentSessionConnected) { var searchFacebookMF = new FacebookMutualFriendsSearch(viewer, viewed, PageBase.GetCurrentUserSession(), FacebookHelper.GetSessionFacebookApp()); var searchFacebookResults = searchFacebookMF.GetResults(); User[] fbMF = (searchFacebookResults != null) ? searchFacebookResults.Get() : new User[] { }; t[3] = DateTime.Now; //using (var db = new ezFixUpDataContext()) { IList<SearchService.MutualFriendsClass> lstFacebookMF = fbMF.Where(user => mfList.All(u => u.Username != user.Username)) .Select(user => new SearchService.MutualFriendsClass { Name = UserSession.GetViewedUserDisplayedNameByUsername(viewer, user.Username), Username = user.Username, PhotoId = 0, PhotoUrl = ImageHandler.CreateFacebookImageUrl(user.FacebookID.Value, fbImageSize), //String.Format("https://graph.facebook.com/{0}/picture?type=square",user.FacebookID), AlreadyRequested = reqList.Contains(user.Username) }).ToList(); if (lstFacebookMF != null && lstFacebookMF.Count > 0) { mfList = mfList.Union(lstFacebookMF).ToList(); } } t[4] = DateTime.Now; } return mfList; //List<SearchService.MutualFriendsClass> lstFacebookMF = searchFacebookMF.GetSavedResults(); //if (lstFacebookMF != null && lstFacebookMF.Count > 0) //{ // lstFacebookMF = lstFacebookMF.Select(f => new SearchService.MutualFriendsClass // { // Username = f.Username, // PhotoId = f.PhotoId, // PhotoUrl = f.PhotoUrl, // AlreadyRequested = reqList.Contains(f.Username) // }).ToList(); // mfList = lstAppMF.Concat(lstFacebookMF).ToList(); //} //return mfList; }
/// <summary> /// Retrieves another cropped image once a capture has been initialized. /// </summary> /// <param name="imageHandler">An <see cref="ImageHandler"/> delegate containing the /// method to call once the image is retrieved.</param> void IPersistableOutput.FetchCapture(ImageHandler imageHandler) { using (Image image = NativeMethods.GetDesktopBitmap(captureRectangle)) imageHandler(image); }
protected void btnupdate_Click(object sender, EventArgs e) { string UploadFolder = "~/ProductImage"; string newFilename = ""; string Spath = ""; if (Request.QueryString["id"] != null && Request.QueryString["id"].ToString() != "") { string strupdcat = "update " + customUtility.DBPrefix + "product set categoryid='" + ddlCategory.SelectedValue.ToString() + "',subcategoryid='" + ddlSubCategory.SelectedValue.ToString() + "',ProductName='" + txtProduct.Text.Replace("'", "''").Trim() + "',CAS='" + txtCAS.Text.Replace("'", "''") + "'"; strupdcat += ",Formula='" + txtFormula.Text.Replace("'", "''") + "',MWeight='" + txtWeight.Text.Replace("'", "''") + "'"; if (fuPImage.HasFile) { if (chkfile(fuPImage.FileName)) { ImageHandler newImg = new ImageHandler(fuPImage.PostedFile, UploadFolder); bool uploadLrg = newImg.UploadImage(); newFilename = newImg.NewFilename; Spath = UploadFolder + "/" + newFilename; ImageResizing imgsize = new ImageResizing(); imgsize.NewFileName = "Large_" + newFilename; imgsize.FolderName = UploadFolder; imgsize.ThumbnailHeight = 156; imgsize.ThumbnailWidth = 221; imgsize.ResizeImage(Server.MapPath(Spath)); imgsize.NewFileName = "Middle_" + newFilename; imgsize.FolderName = UploadFolder; imgsize.ThumbnailHeight = 156; imgsize.ThumbnailWidth = 221; imgsize.ResizeImage(Server.MapPath(Spath)); imgsize.NewFileName = "Small_" + newFilename; imgsize.FolderName = UploadFolder; imgsize.ThumbnailHeight = 100; imgsize.ThumbnailWidth = 200; imgsize.ResizeImage(Server.MapPath(Spath)); imgsize.NewFileName = "Thumb_" + newFilename; imgsize.FolderName = UploadFolder; imgsize.ThumbnailHeight = 75; imgsize.ThumbnailWidth = 150; imgsize.ResizeImage(Server.MapPath(Spath)); strupdcat += ",ProductImage='" + newFilename.ToString() + "'"; } else { lblmessage.Visible = true; lblmessage.Text = "Files having extension .png ,.jpg ,.jpeg ,.gif are allowed"; } } //if (chkfile(fuPImage.FileName)) //{ // fuPImage.SaveAs(Server.MapPath("~/ProductImage/"+fuPImage.FileName.ToString())); // strupdcat += ",ProductImage='" + fuPImage.FileName.ToString() + "'"; //} strupdcat += "where id=" + Request.QueryString["id"].ToString(); bool check = customUtility.CheckDataExists("select * from " + customUtility.DBPrefix + "product where id!=" + Request.QueryString["id"].ToString() + " and productname='" + txtProduct.Text.Replace("'", "''") + "'"); if (check == true) { lblmessage.Text = "Product Name already exists ! Try another Product Name."; } else { customUtility.ExecuteNonQuery(strupdcat); // Response.Write("select * from " + customUtility.DBPrefix + "catalog where productid=" + Request.QueryString["id"].ToString() + " order by id asc"); // Response.End(); DataTable dtCatalog = customUtility.GetTableData("select * from " + customUtility.DBPrefix + "catalog where productid=" + Request.QueryString["id"].ToString() + " order by id asc").Tables[0]; ViewState["noOfRow"] = dtCatalog.Rows.Count.ToString(); if (dtCatalog.Rows.Count > 0) { for (int i = 0; i < dtCatalog.Rows.Count; i++) { Response.Write(Request.Form["txtCatalog" + i].ToString()); Response.End(); if (dtCatalog.Rows[i]["id"].ToString() == Request.Form["hid" + i].ToString()) { string Updatecatalog = "update " + customUtility.DBPrefix + "catalog set CatalogName='" + Request.Form["txtCatalog" + i].ToString() + "',Quantity='" + Request.Form["txtQuantity" + i].ToString() + "',price='" + Request.Form["txtPrice" + i].ToString() + "' where id=" + Request.Form["hid" + i].ToString() + ""; customUtility.ExecuteNonQuery(Updatecatalog); } else { } } } Response.Redirect(ConfigurationManager.AppSettings["WebSitePath"].ToString() + "Admin_Peptech/ManageProduct/ProductList.aspx?Upd=1"); } } }
public async Task <IHttpActionResult> Edit(AdvertisementEditDto editAd) { if (ModelState.IsValid) { var session = await db.Sessions.SingleOrDefaultAsync( QueryHelper.GetSessionObjectValidationQuery(editAd.Session)); if (session != null) { var user = session.User; var adInDb = db.Advertisements.Include(d => d.UserImage) .SingleOrDefault(a => a.Id == editAd.Id && a.User.Id == user.Id); if (adInDb != null) { var isImageEmpty = string.IsNullOrEmpty(editAd.UserImage); //we check if a user has lowered the price of an advertisement to some degree. var isHot = editAd.Price <= adInDb.Price * 3 / 4; //We want to know if a user has uploaded a new image for his/her advertisement if (!isImageEmpty) { adInDb.UserImage = ImageHandler.CreateUserImage(db, user.Id, editAd.UserImage); } else { adInDb.UserImage = null; } adInDb.MedType = editAd.MedType; adInDb.Latitude = editAd.Latitude; adInDb.Longitude = editAd.Longitude; adInDb.LocationRegionId = editAd.LocationRegionId; adInDb.LocationCityId = editAd.LocationCityId; adInDb.LocationProvinceId = editAd.LocationProvinceId; adInDb.Price = editAd.Price; adInDb.Caption = editAd.Caption; adInDb.UpdatedAt = DateTime.Now; //first we have to get rid of old exchange records in database db.Exchanges.RemoveRange(db.Exchanges.Where(x => x.AdvertisementId == adInDb.Id)); if (editAd.ExchangeGames.Count > 0) //we have some games to exchange { foreach (var game in editAd.ExchangeGames) { var newExchange = new Exchange() { AdvertisementId = adInDb.Id, GameId = game }; db.Exchanges.Add(newExchange); } } await db.SaveChangesAsync(); // we re-broadcast this advertisement NotificationGenerator.OldAdvertisementNotification(db, adInDb, isHot); return(Ok()); } return(NotFound()); } return(Unauthorized()); } return(BadRequest()); }
/// <summary> /// Default constructor /// </summary> /// <param name="wingsConnector">To be injected</param> /// <param name="imageHandler">To be injected</param> public WingsController(WingsConnector wingsConnector, ImageHandler imageHandler) { Connector = wingsConnector; ImageHandler = imageHandler; }
private static bool IsSameRgbColor(int i, int j, Color invalidColor, ImageHandler imageHandler) { var currentClr = imageHandler.GetPixelAt1BasedIndex(Convert.ToInt32(i), Convert.ToInt32(j)); return(CommonFunctions.IsSameRgbColor(currentClr, invalidColor)); }
/// <summary> /// Retrieves another cropped image once a capture has been initialized. /// </summary> /// <param name="imageHandler">An <see cref="ImageHandler"/> delegate containing the /// method to call once the image is retrieved.</param> void IPersistableOutput.FetchCapture(ImageHandler imageHandler) { using (Image image = NativeMethods.GetDesktopBitmap(captureRectangle)) imageHandler(image); }
public override void LoadContent(ref ImageHandler Image) { base.LoadContent(ref Image); }
protected string test(object input) { return(ImageHandler.ConvertingPics(input)); }
/// <summary> /// Default constructor /// </summary> /// <param name="hatsConnector">To be injected</param> /// <param name="imageHandler">To be injected</param> public HatsController(HatsConnector hatsConnector, ImageHandler imageHandler) { Connector = hatsConnector; ImageHandler = imageHandler; }
private void CacheImagesOfFriends(HttpContext context, ImageHandler.eFacebookImageType imgSize) { var friendsIDsWithMutualFriends = ((List<MutualFriendItem>)HttpContext.Current.GetSession()["FacebookMutualFriends"]) .Select(f => f.FriendID).Distinct().ToList(); List<string> urlList = friendsIDsWithMutualFriends .Select(fbId => ImageHandler.CreateFacebookImageUrl(fbId, imgSize)) .ToList(); foreach (string url in urlList) { context.Response.Write(String.Format("<img src='{0}' style='display:none;'></img>", url)); } //var lstImagesTags = new List<string>(); //List<Friend> fbFriends; //using (var db = new AspNetDatingDataContext()) //{ // fbFriends = CompiledQueries // .FetchActiveFriendsForUsername(db, PageBase.GetCurrentUserSession().Username) // .Where(u => u.f_is_facebook_friend.HasValue && u.f_is_facebook_friend.Value) // .Skip(lastFriendsPage * 20).Take(40).ToList(); //} //foreach (var fbFriend in fbFriends) //{ // if (!fbFriend.User1.u_facebookid.HasValue) continue; // long fbId = fbFriend.User1.u_facebookid.Value; // string url = ImageHandler.CreateFacebookImageUrl(fbId, imgSize); // lstImagesTags.Add(String.Format("<img src='{0}' style='display:none;'></img>", url)); //} //lastFriendsPage++; //context.Session["LastFriendsViewedPage"] = (lstImagesTags.Count > 0) ? lastFriendsPage : 0; }
public FlipHorizontalStrategy(ImageHandler performer) : base(performer) { }
public virtual void LoadContent(ref ImageHandler Image) { this.Image = Image; }
public FlipVerticalStrategy(ImageHandler performer) : base(performer) { }
private void LoadWorker(object sender, WaitWindowEventArgs e) { var attributes = AttributeGatherers.AttributesFromObject(StreamingContent); if (attributes.Rows.Count > 0) { if (dgvAttributes.InvokeRequired) { dgvAttributes.BeginInvoke((MethodInvoker) delegate { dgvAttributes.DataSource = attributes; }); } else { dgvAttributes.DataSource = attributes; } } //fill the poster picturebox if (!string.IsNullOrEmpty(StreamingContent.StreamInformation.ContentThumbnailUri)) { if (picPoster.InvokeRequired) { picPoster.BeginInvoke((MethodInvoker) delegate { picPoster.BackgroundImage = StreamingContent.StreamInformation.ContentThumbnail ?? ImageHandler.GetPoster(StreamingContent); }); } else { picPoster.BackgroundImage = StreamingContent.StreamInformation.ContentThumbnail ?? ImageHandler.GetPoster(StreamingContent); } } //fill the plot synopsis infobox if (!string.IsNullOrEmpty(StreamingContent.Synopsis)) { if (txtPlotSynopsis.InvokeRequired) { txtPlotSynopsis.BeginInvoke((MethodInvoker) delegate { txtPlotSynopsis.Text = !Methods.AdultKeywordCheck(StreamingContent) ? StreamingContent.Synopsis : @"Plot synopsis for this title is unavailable due to adult content protection"; }); } else { txtPlotSynopsis.Text = !Methods.AdultKeywordCheck(StreamingContent) ? StreamingContent.Synopsis : @"Plot synopsis for this title is unavailable due to adult content protection"; } } //apply content title and enable VLC streaming if (InvokeRequired) { BeginInvoke((MethodInvoker) delegate { itmStream.Enabled = true; Text = StreamingContent.StreamInformation.ContentTitle; Refresh(); }); } else { itmStream.Enabled = true; Text = StreamingContent.StreamInformation.ContentTitle; Refresh(); } //there's content now; so the window isn't stationary anymore. StationaryMode = false; }
public RotateCwStrategy(ImageHandler performer) : base(performer) { }
public void GetInteger_Should_Return_Default_Value_When_Key_Is_Absent() { var result = ImageHandler.GetInteger(new NameValueCollection(), "Key", 2); Assert.Equal(2, result); }
protected BitmapCropAndFilterStrategy(ImageHandler performer) : base(performer) { }
public async Task <IHttpActionResult> Create(AdvertisementCreateDto advertisementCreate) { if (ModelState.IsValid) { var session = await db.Sessions.SingleOrDefaultAsync( QueryHelper.GetSessionObjectValidationQuery(advertisementCreate.Session)); if (session != null) { var user = session.User; var isImageEmpty = string.IsNullOrEmpty(advertisementCreate.UserImage); Models.Image userImage = null; if (!isImageEmpty) { //we write user's uploaded image in memory userImage = ImageHandler.CreateUserImage(db, user.Id, advertisementCreate.UserImage); } var newAdvertisement = new Advertisement() { User = user, MedType = advertisementCreate.MedType, GameId = advertisementCreate.GameId, GameReg = advertisementCreate.GameReg, Latitude = advertisementCreate.Latitude, Longitude = advertisementCreate.Longitude, LocationRegionId = advertisementCreate.LocationRegionId, LocationCityId = advertisementCreate.LocationCityId, LocationProvinceId = advertisementCreate.LocationProvinceId, Price = advertisementCreate.Price, PlatformId = advertisementCreate.PlatformId, Caption = advertisementCreate.Caption, UserImage = userImage, isDeleted = false, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now }; db.Advertisements.Add(newAdvertisement); if (advertisementCreate.ExchangeGames.Count > 0) //we have some games to exchange { foreach (var game in advertisementCreate.ExchangeGames) { var newExchange = new Exchange() { AdvertisementId = newAdvertisement.Id, GameId = game }; db.Exchanges.Add(newExchange); } } await db.SaveChangesAsync(); // Broadcasting NotificationGenerator.NewAdvertisementNotification(db, newAdvertisement); return(Ok(newAdvertisement.Id)); } return(Unauthorized()); } return(BadRequest()); }
public ThresholdBitmapCropAndHandleStrategy(int level, ImageHandler performer) : base(performer) { this.level = level; }
public MainViewController() : base("MainViewController", null) { _source = new TableSource(); _imageHandler = new ImageHandler(); _imageHandler.AssetsLoaded += handleAssetsLoaded; }
public SepiaBitmapCropAndHandleStrategy(ImageHandler performer) : base(performer) { }
private async Task HandleCommandAsync(SocketMessage arg) { MessageHandler handler = new MessageHandler(); var message = arg as SocketUserMessage; if (message == null || message.Author.IsBot) { return; } int argPos = 0; if ((message.HasStringPrefix("!", ref argPos) || message.HasMentionPrefix(Settings._client.CurrentUser, ref argPos)) && !CheckPrivate(message)) { var context = new SocketCommandContext(Settings._client, message); Debugging.Log("Command Handler", $"{context.User.Username} called {message}"); var result = await Settings._commands.ExecuteAsync(context, argPos, Settings._services); if (!result.IsSuccess && result.Error != CommandError.ObjectNotFound || result.Error != CommandError.Exception || result.ErrorReason != "The server responded with error 400: BadRequest") { Debugging.Log("Command Handler", $"Error with command {message}: {result.ErrorReason.Replace(".", "")}", LogSeverity.Warning); if (result.ErrorReason == "Invalid context for command; accepted contexts: DM") { await arg.Channel.SendMessageAsync("", false, handler.BuildEmbed(":no_entry_sign: Whoops! Something went wrong!", "Try messaging that command to me instead!").Build()); } else { await arg.Channel.SendMessageAsync("", false, handler.BuildEmbed(":no_entry_sign: Whoops! Something went wrong!", result.ErrorReason).Build()); } } } else if (CheckPrivate(message)) //direct message { bool AddingToDB = false; var context = new SocketCommandContext(Settings._client, message); Debugging.Log("Command Handler, DM", $"{context.User.Username} sent {message}"); if (!CheckUserInDatabase.Check(context.User.Id.ToString())) // checks if user is in database, if not, add { AddingToDB = true; await arg.Channel.SendMessageAsync("", false, handler.BuildEmbed("Hi there!", "Looks like we've never met before. Nice to meet you! I'm going to quickly add you to my database...", ImageHandler.GetImageUrl("ahriwave")).Build()); User newUser = new User(context.User.Id.ToString(), context.User.Username); if (newUser.AddToDatabase()) { await arg.Channel.SendMessageAsync("", false, handler.BuildEmbed("All done!", "You're ready to go! Use `help` to see what I can do!")); } else { await arg.Channel.SendMessageAsync("", false, handler.BuildEmbed("Hmm... Something went wrong!", "I couldn't add you to my database. Go ahead and try again!")); } } var result = await Settings._commands.ExecuteAsync(context, argPos, Settings._services); if (!result.IsSuccess && result.Error != CommandError.ObjectNotFound || result.Error != CommandError.Exception) { if (AddingToDB) { AddingToDB = false; } else { Debugging.Log("Command Handler, DM", $"Error with command {message}: {result.ErrorReason.Replace(".", "")}", LogSeverity.Warning); await arg.Channel.SendMessageAsync("", false, handler.BuildEmbed(":no_entry_sign: Whoops! Something went wrong!", result.ErrorReason).Build()); } } } }
public GrayscaleBitmapCropAndHandleStrategy(ImageHandler performer) : base(performer) { }
private void pictureBox2_Click(object sender, EventArgs e) { ImageHandler IH = new ImageHandler(); IH.CreateFileDialog(ImageTypes.Avatar); }
public void CreateGif(List <string> ListOfImagePaths, string PlayerImagesFolder, long ParamPlayerID, ref string Msg, ref bool status, Controller ctrl) { string[] imageFilePaths = ListOfImagePaths.ToArray();// new string[] { "D:\\temp\\01.png", "D:\\temp\\02.png", "D:\\temp\\03.png" }; int MAX_Width = 0; int MAX_Height = 0; foreach (var item in imageFilePaths) { using (Image imgPhoto = Image.FromFile(item)) { //create a image object containing the photograph to watermark int phWidth = imgPhoto.Width; if (MAX_Width < phWidth) { MAX_Width = phWidth; } int phHeight = imgPhoto.Height; if (MAX_Height < phHeight) { MAX_Height = phHeight; } } } string fileNameOnly = Guid.NewGuid().ToString() + ".gif"; string outputFilePath = Path.Combine(PlayerImagesFolder, fileNameOnly); ImageHandler imageHandler = new ImageHandler(); List <Image> ListOfImages = new List <Image>(); int i = 500; foreach (var item in imageFilePaths) { using (Image imgPhoto = Image.FromFile(item)) { //create a image object containing the photograph to watermark Size size = new Size(MAX_Width, MAX_Height); ListOfImages.Add(imageHandler.FixedSize(imgPhoto, size.Width, size.Height)); // ListOfImages.Add(imageHandler.Resize_Usman(imgPhoto, size, PlayerImagesFolder, i)); } i = i + 1; } AnimatedGifEncoder e = new AnimatedGifEncoder(); e.SetSize(MAX_Width, MAX_Height); e.Start(outputFilePath); e.SetDelay(1000); //-1:no repeat,0:always repeat e.SetRepeat(0); foreach (var item in ListOfImages) { e.AddFrame(item); } //for (int i = 0, count = imageFilePaths.Length; i < count; i++) //{ // e.AddFrame(Image.FromFile(imageFilePaths[i])); //} e.Finish(); e.SetDispose(0); /* extract Gif */ //string outputPath = "D:\\temp"; //GifDecoder gifDecoder = new GifDecoder(); //gifDecoder.Read("D:\\temp\\Finalsss.gif"); //for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++) //{ // Image frame = gifDecoder.GetFrame(i); // frame i // frame.Save(outputPath + Guid.NewGuid().ToString() + ".png", ImageFormat.Png); //} //Add it to Database PlayerImagesExt PlayerImg = new PlayerImagesExt() { PlayerID = ParamPlayerID, FileName = fileNameOnly, IsAnimated = true, Display = true, DefaultImage = false }; CreateOrUpdate(ref PlayerImg, ref Msg, ref status, ctrl); }
private void MasterGenerator() { string vendorID, vendorName, vendorDescription, vendorPostcode, vendorRating, imageLoc; string SQLQuery = "SELECT * FROM vendors"; using (DataTable DataResults = FeedMeLogic.Data.DAL.ExecCommand(SQLQuery)) { int vendorAmount = DataResults.Rows.Count; VendorAmountLabel.Text = string.Format("There are currently {0} restraunts/food places near you", vendorAmount.ToString()); //Updates Text to Match No of Vendors #region Initiaizling Location & Size For Controls //Initializing Height & Location Variables (Information from Design Version) Size vendorPanelSize = new Size(711, 96); Size TitleSize = new Size(142, 30); Size DescSize = new Size(556, 47); Size RatingSize = new Size(80, 21); Size PostcodeSize = new Size(84, 21); Size PictureBoxSize = new Size(127, 86); Point TitleLoc = new Point(344, 5); Point DescLoc = new Point(146, 36); Point RatingLoc = new Point(485, 5); Point PostcodeLoc = new Point(567, 5); Point PictureBoxLoc = new Point(4, 5); Font DefaultFont = new Font("Nirmala UI", 12, FontStyle.Regular); Font TitleFont = new Font("Nirmala UI", 14, FontStyle.Bold); #endregion Initiaizling Location & Size For Controls //string DefaultFnt = "Nirmala UI"; int maxGen = vendorAmount; #region Iterating Through Each Vendor for (int i = 0; i < maxGen; i++) { #region Getting Variables vendorID = DataResults.Rows[i][0].ToString(); vendorName = DataResults.Rows[i][1].ToString(); vendorDescription = DataResults.Rows[i][2].ToString(); vendorPostcode = ("(" + DataResults.Rows[i][4].ToString() + ")"); //vendorRating = DataResults.Rows[i][6].ToString(); vendorRating = "⭐⭐⭐⭐⭐"; imageLoc = ImageHandler.GetImage(ImageTypes.Avatar, DataResults.Rows[i][10].ToString()); #endregion Getting Variables #region Creating & Adding Event Handlers To Each Control Panel vendorPanelObject = GenControls.AddPanel(vendorName, Color.White, vendorPanelSize); Label vendorTitleLabel = GenControls.AddLabel(vendorName, vendorName, TitleLoc, TitleFont, Color.Black, Color.Transparent, TitleSize, true); Label vendorDescLabel = GenControls.AddLabel(vendorName + "Desc", vendorDescription, DescLoc, DefaultFont, Color.Black, Color.Transparent, DescSize, false); RatingLoc = new Point(vendorTitleLabel.Location.X + vendorTitleLabel.Width - 15, vendorTitleLabel.Location.Y); Label vendorRatingLabel = GenControls.AddLabel(vendorName + "Rating", vendorRating, RatingLoc, DefaultFont, Color.Black, Color.Transparent, RatingSize, true); PostcodeLoc = new Point(vendorRatingLabel.Location.X + vendorRatingLabel.Width - 15, vendorRatingLabel.Location.Y); Label vendorPostcodeLabel = GenControls.AddLabel(vendorName + "PostCode", vendorPostcode, PostcodeLoc, DefaultFont, Color.LightGray, Color.Transparent, PostcodeSize, true); PictureBox vendorPictureBox = GenControls.AddPictureBox(vendorName, PictureBoxLoc, PictureBoxSize); vendorPictureBox.ImageLocation = imageLoc; Control[] controlArray = new Control[] { vendorTitleLabel, vendorDescLabel, vendorRatingLabel, vendorPostcodeLabel, vendorPictureBox }; foreach (Control curControl in controlArray) { //Add Event Handlers Below curControl.Click += new EventHandler(OpenVendor); curControl.MouseMove += new MouseEventHandler(CursorChangeArgs); vendorPanelObject.Controls.Add(curControl); } VendorsFlowPanel.Controls.Add(vendorPanelObject); vendorPanelObject.Click += new EventHandler(OpenVendor); vendorPanelObject.MouseMove += new MouseEventHandler(CursorChangeArgs); #endregion Creating & Adding Event Handlers To Each Control } #endregion Iterating Through Each Vendor } }
public IEnumerable <AlbumDto> Get() { var data = mapper.Map <IEnumerable <AlbumDto> >(albumRepo.GetAll()); return(data.Select(x => { x.AlbumArt = ImageHandler.CreateBase64Images(Path.Combine(environment.WebRootPath, x.AlbumArt)); return x; }).AsEnumerable()); }
/// <summary> /// Default constructor /// </summary> /// <param name="bodiesConnector">To be injected</param> /// <param name="imageHandler">To be injected</param> public BodiesController(BodiesConnector bodiesConnector, ImageHandler imageHandler) { Connector = bodiesConnector; ImageHandler = imageHandler; }
public override ImageHandler Read(BinaryReader reader) { var bmp = new Bitmap(reader.BaseStream); return(ImageHandler.FromBitmapAsGreyscale(bmp)); // ImageHandler.FromBitmap(bmp); }
private void SaveImages(object sender, DoWorkEventArgs e) { // method using Background Worker to report progress var savePath = e.Argument as string; const int numSteps = 7; // max number of times progress change is reported var step = (int)Math.Round(1.0 / (numSteps + 2) * 100, 0); var progress = 0; // Create temp folder for zipping files var tmpZipDir = Path.Combine(tmpWorkDir, "cis_zip"); if (Directory.Exists(tmpZipDir)) { DirectoryExtension.SafeDelete(tmpZipDir, true); } Directory.CreateDirectory(tmpZipDir); // convert user png images to dds images for (int i = 0; i < imageArray.GetUpperBound(0); i++) { progress += step; bwSaveImages.ReportProgress(progress, "Converting user PNG images ... " + i.ToString()); if (imageArray[i, 3] != null) // user has specified a replacement image { // CRITICAL PATH AND ARGS var srcPath = imageArray[i, 3]; var destPath = Path.Combine(tmpZipDir, Path.GetFileName(imageArray[i, 2])); ExternalApps.Png2Dds(srcPath, destPath, ImageHandler.Size2IntX(imageArray[i, 1]), ImageHandler.Size2IntY(imageArray[i, 1])); } } progress += step; bwSaveImages.ReportProgress(progress, "Saving Intro Screens Template file ... "); // Write ini file setup.smb var iniFile = Path.Combine(tmpZipDir, "setup.smb"); Configuration iniCFG = new Configuration(); iniCFG["General"].Add(new Setting("author", String.IsNullOrEmpty(txtAuthor.Text) ? "CSC" : txtAuthor.Text)); iniCFG["General"].Add(new Setting("seqname", String.IsNullOrEmpty(txtSeqName.Text) ? "SystemSaved" : txtSeqName.Text)); iniCFG["General"].Add(new Setting("cscvers", ToolkitVersion.version)); iniCFG["General"].Add(new Setting("modified", DateTime.Now.ToShortDateString())); iniCFG.Save(iniFile); // Zip intro sequence *.cis file ExternalApps.InjectZip(tmpZipDir, savePath, false, true); }
public void update(ref Bitmap bitmap, DateTime time) { ImageHandler blend = new ImageHandler(bitmap); // Lock bitmaps day.lockBitmap(); night.lockBitmap(); blend.lockBitmap(); // Calculate the Greenwich Sidereal Time double GST = getGreenwichSiderealTime(time); // Calculate the solar right ascension and declination double alpha = getSolarRightAscension(time); double delta = getSolarDeclination(time); // Loop over the y-pixels of the night/day images int i_x; int i_y; for (i_x = 0; i_x < this.n_x; i_x++) { // Calculate the longitude double longitude = 180 - (i_x + 0.5) / this.n_x * 360; // Calculate the solar hour angle double HA = GST * 360 / 24 - longitude - alpha; for (i_y = 0; i_y < this.n_y; i_y++) { // Calculate the latitude double latitude = 90 - (i_y + 0.5) / this.n_y * 180; // Calculate the altitude of the sun double alt = getAltitude(HA, delta, latitude, longitude); // Work out the interpolation factor for drawing the pixel double intFactor; if (alt > dayAltMin) { intFactor = 1; } else if (alt < nightAltMax) { intFactor = 0; } else { intFactor = (alt - nightAltMax) / (dayAltMin - nightAltMax); } // Get the RGB pixels of the day and night images int dayRGB = (int)this.day.getPixel(i_x, i_y); int nightRGB = (int)this.night.getPixel(i_x, i_y); int dayR = dayRGB >> 16 & 0xFF; int dayG = dayRGB >> 8 & 0xFF; int dayB = dayRGB & 0xFF; int nightR = nightRGB >> 16 & 0xFF; int nightG = nightRGB >> 8 & 0xFF; int nightB = nightRGB & 0xFF; // Calculate the interpolated value of the blended pixel int blendedRGB = (int)(dayR * intFactor + nightR * (1 - intFactor)) << 16 | (int)(dayG * intFactor + nightG * (1 - intFactor)) << 8 | (int)(dayB * intFactor + nightB * (1 - intFactor)); blend.setPixel(i_x, i_y, blendedRGB); } } // Lock bitmaps day.unlockBitmap(); night.unlockBitmap(); blend.unlockBitmap(); }
public void ImageHandlerClose() { // Verify that it is possible to close an empty object. ImageHandler handler = new ImageHandler(); handler.Close(); // We can not verify that if the image handler is not empty, then // the image list is disposed, but we can verify that at least it // is released. handler = new ImageHandler(typeof(ImageHandlerTest).Assembly.GetManifestResourceStream("Resources.ImageList.bmp")); Assert.IsNotNull(handler.ImageList); handler.Close(); Assert.IsNull(handler.ImageList); }
ImageView GetNativeImageView(ImageHandler imageHandler) => imageHandler.NativeView;
bool GetNativeIsAnimationPlaying(ImageHandler imageHandler) => GetNativeImageView(imageHandler).Drawable is IAnimatable animatable && animatable.IsRunning;
// Use this for initialization void Start() { image = GameObject.Find ("Image").GetComponent<ImageHandler> (); }