/* * public async Task<string> PomfImageUpload(Image<Rgba32> img) * { * string hostUrl = "https://mixtape.moe/upload.php"; * MemoryStream imgStream = new MemoryStream(); * img.Save(imgStream); * imgStream.Seek(0, SeekOrigin.Begin); * using (var client = new HttpClient()) * using (var formData = new MultipartFormDataContent()) * { * formData.Add(new StreamContent(imgStream), "files", "filename.png"); * var resp = await client.PostAsync(hostUrl, formData); * if (resp.IsSuccessStatusCode) * { * string jsonStr = await resp.Content.ReadAsStringAsync(); * var uploadJson = JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>(jsonStr); * string uploadUrl = uploadJson["files"][0]["url"]; * Console.WriteLine("Uploaded success to pomf, url is : " + uploadUrl); * return uploadUrl; * } * else * { * Console.WriteLine("Failed upload."); * return ""; * } * } * //string res = await Provider.GetService<HttpService>().Post(hostUrl, $"files: [{imgStream.To}]"); * var uploadJson = JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>(res); * string uploadUrl = uploadJson["files"][0]["url"]; * Console.WriteLine("Uploaded success to pomf, url is : " + uploadUrl); * return uploadUrl; * }*/ public async Task <IImage> UploadImage(Image <Rgba32> img) { MemoryStream imgStream = new MemoryStream(); img.Save(imgStream); imgStream.Seek(0, SeekOrigin.Begin); string imgSize = Provider.GetService <MathService>().BytesToNiceSize(imgStream.Length); try { ImgurClient client = new ImgurClient(Provider.GetService <Config>().ImgurClientId, Provider.GetService <Config>().ImgurClientSecret); ImageEndpoint endpoint = new ImageEndpoint(client); IImage imgData = await endpoint.UploadImageStreamAsync(imgStream); ConsoleEx.WriteColoredLine(Discord.LogSeverity.Info, ConsoleTextFormat.TimeAndText, $"Successfully uploaded image to Imgur. [{imgSize}]"); imgStream.Dispose(); return(imgData); } catch (Exception ex) { string failMessage = $"Failed uploading image to Imgur. [{imgSize}];\n{ex.Message}"; ConsoleEx.WriteColoredLine(Discord.LogSeverity.Critical, ConsoleTextFormat.TimeAndText, failMessage); imgStream.Dispose(); return(null); } }
public string UploadImage(byte[] msgArray, string user_id, string display_name) { var today = timeService.GetLocalDateTime(LocalTimeService.CHINA_STANDARD_TIME); var client = new ImgurClient(IMGUR_CLIENT_ID, IMGUR_CLIENT_SECRET); var endpoint = new ImageEndpoint(client); IImage image; Stream stream = new MemoryStream(msgArray); using (stream) { image = endpoint.UploadImageStreamAsync(stream).GetAwaiter().GetResult(); } using (var db = new LineModel()) { var instance = new UploadImage { addTime = today, flg = false, imageUrl = image.Link, userId = user_id, userName = display_name }; db.UploadImage.Add(instance); db.SaveChanges(); var status = db.UploadStatus.Where(x => x.UserId == user_id && x.CommandStr == "--upload").ToList(); db.UploadStatus.RemoveRange(status); db.SaveChanges(); } return(image.Link); }
public APIResult TestImgur() { var client = new ImgurClient("2f3ed3db83e866d", "62a894b5e1dd5ed77cc5b4f10eea25e3ebc3e816" , new OAuth2Token("654c446bd2f20543284db4a2d986ea234d81b98b" , "e3100d2d2fc8b14e9131dc1aad5b9a24ca8ee22c" , "bearer" , "132433023" , "frankimg" , 315360000)); var endpoint = new ImageEndpoint(client); var endpointAlbum = new AlbumEndpoint(client); IImage image; bool success = false; //取得圖片檔案FileStream using (var fs = new FileStream(@"D:\Documents\build_school\project\finalProject1\SurvivalGameVer2\SurvivalGame\Assets\images\Product1.png", FileMode.Open)) { image = endpoint.UploadImageStreamAsync(fs).GetAwaiter().GetResult(); success = endpointAlbum.AddAlbumImagesAsync("ZeSZMYK", new List <string>() { image.Id }).GetAwaiter().GetResult(); } return(new APIResult() { IsSuccess = true, //顯示圖檔位置 Data = $"Image uploaded.Image Url: + {image.Link} ,ImgId:{image.Id} ,success: {success}" }); }
public async Task <string> UploadImage(IFormFile image) { try { var clientId = _config.GetSection("ImgurSettings").GetValue <string>("ClientId"); var clientSecret = _config.GetSection("ImgurSettings").GetValue <string>("ClientSecret"); var client = new ImgurClient(clientId, clientSecret); var endpoint = new ImageEndpoint(client); if (image.Length > 0) { var fileStream = image.OpenReadStream(); IImage uploadImage = await endpoint.UploadImageStreamAsync(fileStream); return(uploadImage.Link); } else { throw new ImgurException("Image size = 0"); } } catch (ImgurException imgurEx) { throw imgurEx; } }
public async Task Create(PostBLL post) //post { if (post == null) { throw new Exception("Post is null"); } string path; var rand = new Random(); do { path = @"C:\data\Projects\Finalv2\photo_archive\WebAPI\App_Data\" + rand.Next(1000).ToString() + ".jpg"; }while (File.Exists(path)); string base64 = post.Content.Substring(post.Content.LastIndexOf(',') + 1); File.WriteAllBytes(path, Convert.FromBase64String(base64)); var client = new ImgurClient("", ""); var endpoint = new ImageEndpoint(client); IImage image; using (var fs = new FileStream(path, FileMode.Open)) { image = await endpoint.UploadImageStreamAsync(fs); } post.Url = image.Link; //File.Delete(path); var mapper = new Mapper(BLLtoDAL); Post postDAL = mapper.Map <PostBLL, Post>(post); db.Post.Create(postDAL); db.Save(); }
public string upload_image(string imageLocation) { var imageLink = string.Empty; try { var client = new ImgurClient(_configuration.ImageUploadClientId, _configuration.ImageUploadClientSecret); var endpoint = new ImageEndpoint(client); IImage image; using (var imageStream = new FileStream(imageLocation, FileMode.Open, FileAccess.Read)) { image = endpoint.UploadImageStreamAsync(imageStream).GetAwaiter().GetResult(); } imageLink = image.Link; this.Log().Debug("Image uploaded to '{0}' from '{1}'".format_with(imageLink, imageLocation)); } catch (ImgurException ex) { this.Log().Warn("Upload failed for image:{0} {1}".format_with(Environment.NewLine, ex.Message)); } return(imageLink); }
public async Task Upload(Album album) { ImageEndpoint endpoint = new ImageEndpoint(await ImgurHelper.GetClient()); using (Stream src = File.OpenRead(Path.Combine(album.Root, FileName))) { await endpoint.UploadImageStreamAsync(src, album.Id, Name); } }
private static async Task <string> UploadFile(IFormFile file, int productId) { const string clientId = "b6b6978e249571d"; const string secret = "1be7229d4f3819aa4a726a7933db245ec1b0ad97"; var client = new ImgurClient(clientId, secret); var endpoint = new ImageEndpoint(client); var image = await endpoint.UploadImageStreamAsync(file.OpenReadStream()); return(image.Link); }
public string UploadImage(string source) { var client = new ImgurClient("3bfa9e553867a45"); var endpoint = new ImageEndpoint(client); IImage image; var fs = new FileStream(@source, FileMode.Open); image = endpoint.UploadImageStreamAsync(fs).GetAwaiter().GetResult(); Console.WriteLine(image.Link); return(image.Link); }
/// <summary> /// Upload Image to Imgur Album /// </summary> /// <param name="stream">The Image as any sort of Stream</param> /// <param name="windowName">The name of the Window</param> /// <param name="albumId">The ID of the Album, or for anonymous Albums: DeleteHash</param> public async Task UploadToAlbum(Stream stream, string windowName, string albumId) { //Set Stream Position to beginning stream.Position = 0; ImageEndpoint endpoint = new ImageEndpoint(_client); string title = string.IsNullOrWhiteSpace(windowName) ? null : windowName; await endpoint.UploadImageStreamAsync(stream, albumId, title); }
//Upload Image to Imgur private string UploadImage2Imgur(byte[] bytes) { var Imgur_CLIENT_ID = System.Configuration.ConfigurationManager.AppSettings["Imgur_CLIENT_ID"]; var Imgur_CLIENT_SECRET = System.Configuration.ConfigurationManager.AppSettings["Imgur_CLIENT_SECRET"]; //建立 ImgurClient準備上傳圖片 var client = new ImgurClient(Imgur_CLIENT_ID, Imgur_CLIENT_SECRET); var endpoint = new ImageEndpoint(client); IImage image; //上傳Imgur image = endpoint.UploadImageStreamAsync(new MemoryStream(bytes)).GetAwaiter().GetResult(); return(image.Link); }
/// <summary> /// Загрузка картинки /// </summary> /// <param name="file">файл</param> /// <param name="ct"></param> /// <returns></returns> public async Task <IImage> UploadFileAsync(IFormFile file, CancellationToken ct) { try { var client = new ImgurClient(ImgurClientId, ImgurClientSecretId); var endpoint = new ImageEndpoint(client); return(await endpoint.UploadImageStreamAsync(file.OpenReadStream()).ConfigureAwait(false)); } catch (ImgurException e) { throw; } }
public async Task <string> UploadImageFromFileAsync(StorageFile photo) { IImage image = await Task.Run(async() => { using (var fs = new FileStream(photo.Path, FileMode.Open)) { image = await endpoint.UploadImageStreamAsync(fs).ConfigureAwait(false); } return(image); }).ConfigureAwait(false); Debug.WriteLine("Image uploaded. Image Url: " + image.Link); return(image.Link); }
//Upload Image to Imgur private string UploadImage2Imgur(byte[] bytes) { var Imgur_CLIENT_ID = System.Configuration.ConfigurationManager.AppSettings["b04319825cad230"]; var Imgur_CLIENT_SECRET = System.Configuration.ConfigurationManager.AppSettings["355789ea8bc39bf1232ca21138418f79f36a1a01"]; //建立 ImgurClient準備上傳圖片 var client = new ImgurClient(Imgur_CLIENT_ID, Imgur_CLIENT_SECRET); var endpoint = new ImageEndpoint(client); IImage image; //上傳Imgur image = endpoint.UploadImageStreamAsync(new MemoryStream(bytes)).GetAwaiter().GetResult(); return(image.Link); }
public async Task UploadStreamBinaryAsync_WithImageNull_ThrowsArgumentNullException() { var client = new ImgurClient("123", "1234"); var endpoint = new ImageEndpoint(client); var exception = await Record.ExceptionAsync( async() => await endpoint.UploadImageStreamAsync(null).ConfigureAwait(false)) .ConfigureAwait(false); Assert.NotNull(exception); Assert.IsType <ArgumentNullException>(exception); }
/// <summary> /// The checkCommand. /// </summary> /// <param name="message">The message<see cref="CommandMessage"/>.</param> private void checkCommand(CommandMessage message) { message.commandType = message.Parameters[1]; switch (message.commandType) { case Command.SetUserName: prefix = message.Parameters[2]; break; case (string)Command.Clear: Application.Current.Dispatcher.Invoke(() => ViewModel.Messages.Clear()); break; case Command.SetIp: break; case Command.Help: break; case Command.SetImage: try { var client = new ImgurClient("3bfa9e553867a45"); var endpoint = new ImageEndpoint(client); IImage image; using (var fs = new FileStream(message.Parameters[2], FileMode.Open)) { image = endpoint.UploadImageStreamAsync(fs).GetAwaiter().GetResult(); } profileSource = image.Link; Console.WriteLine(image.Link); } catch (ImgurException imgurEx) { Debug.Write(imgurEx.Message); } break; case Command.SetColor: nameColor = message.Parameters[2]; break; default: StringMessage stringMessage = new StringMessage("Uknown command", "Client", null, null); Application.Current.Dispatcher.Invoke(() => ViewModel.Messages.Clear()); break; } }
public string UploadPhoto(string localPath, string title) { IImage image; using (var fileStream = new FileStream(localPath, FileMode.Open)) { image = uploader .UploadImageStreamAsync(fileStream) .GetAwaiter() .GetResult(); } return(image.Link); }
/// <summary> /// Upload Image to Imgur /// </summary> /// <param name="stream">The Image as any sort of Stream</param> /// <param name="windowName">The name of the Window</param> /// <returns>The Link to the uploaded Image</returns> public async Task <string> Upload(Stream stream, string windowName = null) { //Set Stream Position to beginning stream.Position = 0; ImageEndpoint endpoint = new ImageEndpoint(_client); string title = string.IsNullOrWhiteSpace(windowName) ? strings.uploadTitle : $"{windowName} - ({strings.uploadTitle})"; //TODO: use title or null? IImage image = await endpoint.UploadImageStreamAsync(stream, null, null, "https://mrousavy.github.io/ImgurSniper"); return(image.Link); }
public async Task <string> UploadImage(Stream Stream) { try { var Image = await Endpoint.UploadImageStreamAsync(Stream); return(Image.Link); } catch (ImgurException Exception) { Global.Logger.Log(ConsoleColor.Red, Modules.LogType.Imgur, "Upload", "An error occured while uploading an image:" + Environment.NewLine + Exception.Message); } return(""); }
/// <summary> /// Upload Image to Imgur /// </summary> /// <param name="bimage">The Image as byte[]</param> /// <param name="windowName">The name of the Window</param> /// <returns>The Link to the uploaded Image</returns> public async Task <string> Upload(byte[] bimage, string windowName) { ImageEndpoint endpoint = new ImageEndpoint(_client); IImage image; using (MemoryStream stream = new MemoryStream(bimage)) { string title = string.IsNullOrWhiteSpace(windowName) ? strings.uploadTitle : $"{windowName} - (" + strings.uploadTitle + ")"; image = await endpoint.UploadImageStreamAsync(stream, null, title, "https://mrousavy.github.io/ImgurSniper"); } return(image.Link); }
async Task IApi.UploadImage(Windows.Storage.StorageFile file, string name, string description) { try { IImage image; using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { image = await imageEndpoint.UploadImageStreamAsync(fs.AsStream(), null, name, description); } } catch (ImgurException imgurEx) { Debug.Write("An error occurred uploading an image to Imgur."); Debug.Write(imgurEx.Message); } }
public async Task <IActionResult> Upload(List <IFormFile> files) { long size = files.Sum(f => f.Length); // full path to file in temp location var filePath = Path.GetTempFileName(); List <Image> newImages = new List <Image>(); foreach (var imageFile in files) { if (imageFile != null && imageFile.Length > 0) { try { var file = imageFile; var client = new ImgurClient("aa6b9c5aa286ac1", "1e585413d574918e61c1a2577962c7e67b70cf0a"); var endpoint = new ImageEndpoint(client); IImage image; // string uploads = Path.Combine(_appEnvironment.WebRootPath, "uploads\\img"); // string fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName); var fs = file.OpenReadStream(); using (fs) { image = await endpoint.UploadImageStreamAsync(fs); Console.WriteLine(image); } newImages.Add(new Image(file.FileName, image.Link)); Debug.Write("Image uploaded. Image Url: " + image.Link); } catch (ImgurException imgurEx) { Debug.Write("An error occurred uploading an image to Imgur."); Debug.Write(imgurEx.Message); } } } UpateJsonStorage(newImages); return(new JsonResult(newImages)); }
public ActionResult UploadFile2Cloud(string updatedata, string form) { var client = new ImgurClient("f4698b7dc49d5f0", "109e94774eab1e47496e875b4e55bc6b6e59140f"); var endpoint = new ImageEndpoint(client); IImage image; //取得圖片檔案FileStream using (var fs = new FileStream(form, FileMode.Open)) { image = endpoint.UploadImageStreamAsync(fs).GetAwaiter().GetResult(); } var link = JsonConvert.SerializeObject(image.Link); link = link.Replace("\"", ""); return(Json(link, JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult> PutMyDog(long id, IFormFile image) { var user = GetUser(); if (user == null) { return(Unauthorized()); } var dog = context.Dogs.FirstOrDefault(dog => dog.Id == id && dog.OwnerId == user.Id); if (dog == null) { return(BadRequest(Error.BadDogId())); } if (image == null) { dog.Avatar = null; await context.SaveChangesAsync(); } else { if (image.ContentType.Split('/').FirstOrDefault() != "image") { return(BadRequest(Error.FileUploadError("Bad content type"))); } try { var endpoint = new ImageEndpoint(imgur); var result = await endpoint.UploadImageStreamAsync(image.OpenReadStream()); dog.Avatar = result.Link; await context.SaveChangesAsync(); } catch (ImgurException ex) { return(BadRequest(Error.FileUploadError(ex.Message))); } } return(Ok()); }
public static async Task postImageToImgur(string imagePath) { try { var client = new ImgurClient(Imgur.IMGUR_CLIENT_ID, Imgur.IMGUR_CLIENT_SECRET); var endpoint = new ImageEndpoint(client); IImage image; using (var fs = new FileStream(imagePath, FileMode.Open)) { image = await endpoint.UploadImageStreamAsync(fs); } IMAGE_URL = image.Link; } catch (ImgurException imgurEx) { IMAGE_URL = imgurEx.Message; } }
public string UploadImage() { try { var client = new ImgurClient("3123b60aeca7a22", "eefad4cbef84e409672fc1ee1716ecbb76bff5dc"); var endpoint = new ImageEndpoint(client); IImage image; using (var fs = flpFotoPerfil.PostedFile.InputStream /*new FileStream(link, FileMode.Open)*/) { image = endpoint.UploadImageStreamAsync(fs).GetAwaiter().GetResult(); } return(image.Link); } catch (ImgurException) { return(null); } }
//poste une image depuis la bibliothèque d'images /** * Post a picture */ public async void postImage(string filename) { var client_post = new ImgurClient(client_id, imgur_token); var endpoint_post = new ImageEndpoint(client_post); IImage image = null; await Task.Run(() => { Task.Yield(); using (var fs = new FileStream(@"C:\Users\Léo\Pictures\" + filename, FileMode.Open)) { image = endpoint_post.UploadImageStreamAsync(fs).Result; } }); Windows.UI.Xaml.Controls.Image imgImgur2 = new Windows.UI.Xaml.Controls.Image(); imgImgur2.Source = new BitmapImage(new Uri(image.Link, UriKind.Absolute)); imgImgur2.Name = image.Id; }
public async Task UploadImageStreamAsync_WithImage_AreEqual() { var client = new ImgurClient(ClientId, ClientSecret); var endpoint = new ImageEndpoint(client); IImage image = null; using (var fs = new FileStream("banana.gif", FileMode.Open)) { image = await endpoint.UploadImageStreamAsync(fs, null, "stream test title!", "stream test desc!"); } Assert.IsFalse(string.IsNullOrEmpty(image.Id)); Assert.AreEqual("stream test title!", image.Title); Assert.AreEqual("stream test desc!", image.Description); await GetImageAsync_WithImage_AreEqual(image); await UpdateImageAsync_WithImage_AreEqual(image); await DeleteImageAsync_WithImage_IsTrue(image); }
//public OAuth2Token CreateToken() //{ // var token = new OAuth2Token(TOKEN_ACCESS, REFRESH_TOKEN, TOKEN_TYPE, ID_ACCOUNT, IMGUR_USER_ACCOUNT, int.Parse(EXPIRES_IN)); // return token; //} //Use it only if your token is expired //public Task<IOAuth2Token> RefreshToken() //{ // var client = new ImgurClient(CLIENT_ID, CLIENT_SECRET); // var endpoint = new OAuth2Endpoint(client); // var token = endpoint.GetTokenByRefreshTokenAsync(REFRESH_TOKEN); // return token; //} public async Task <Uri> UploadImage(IFormFile file) { try { var client = new ImgurClient(CLIENT_ID, CLIENT_SECRET); var endpoint = new ImageEndpoint(client); Imgur.API.Models.IImage image; //Here you have to link your image location //using (var fs = new FileStream(@"E:\repos\MeowForums\MeowForums\wwwroot\images\forum-logo-s.png", FileMode.Open)) //{ // image = await endpoint.UploadImageStreamAsync(fs); //} using (var mem = file.OpenReadStream()) { //using (var mem2 = new MemoryStream()) //{ // using (var img = SixLabors.ImageSharp.Image.Load(mem, out IImageFormat format)) // { // img.Mutate(i => i.Resize // ( // new ResizeOptions // { // Size = new SixLabors.Primitives.Size(140, 140), // Mode = ResizeMode.Crop // } // )); // img.Save(mem2, format); // image = await endpoint.UploadImageStreamAsync(mem2); // } //} image = await endpoint.UploadImageStreamAsync(mem); } Debug.Write("Image uploaded. Image Url: " + image.Link); return(new Uri(image.Link)); } catch (ImgurException imgurEx) { Debug.Write("Error uploading the image to Imgur"); Debug.Write(imgurEx.Message); } return(new Uri(string.Empty)); }
public async Task <string> UploadPhoto(IFormFile photo) { try { var client = new ImgurClient("0a97710cb62c21f", "2e503f82b29caf7f672fb4ca4ddc3ebb122d5431"); var endpoint = new ImageEndpoint(client); IImage image; using (var fs = photo.OpenReadStream()) { image = await endpoint.UploadImageStreamAsync(fs); } //var order = _context.Orders.FirstOrDefault(x => x.Id == orderId); return(image.Link); } catch (Exception) { return(string.Empty); } }