protected void SelectImage(object sender, EventArgs e) { RenameImageButton.Enabled = (ImageList.Items.Count != 0); DeleteImageButton.Enabled = (ImageList.Items.Count != 0); ResizeImageButton.Enabled = (ImageList.Items.Count != 0); ResizeWidth.Enabled = (ImageList.Items.Count != 0); ResizeHeight.Enabled = (ImageList.Items.Count != 0); if (ImageList.Items.Count == 0) { Image1.ImageUrl = ""; ResizeWidth.Text = ""; ResizeHeight.Text = ""; return; } Image1.ImageUrl = ImageFolder + ImageList.SelectedValue + "?" + new Random().Next(1000); ImageMedia img = ImageMedia.Create(File.ReadAllBytes(FileImageFolder + ImageList.SelectedValue)); ResizeWidth.Text = img.Width.ToString(); ResizeHeight.Text = img.Height.ToString(); ImageAspectRatio.Value = "" + img.Width / (float)img.Height; int pos = ImageList.SelectedItem.Text.LastIndexOf('.'); if (pos == -1) { return; } RenameImageButton.OnClientClick = "var name = prompt('Enter new filename:','" + ImageList.SelectedItem.Text.Substring(0, pos) + "'); if (name == null || name == '') return false; document.getElementById('" + NewImageName.ClientID + "').value = name + '" + ImageList.SelectedItem.Text.Substring(pos) + "';"; OkButton.OnClientClick = "window.top.opener.CKEDITOR.dialog.getCurrent().setValueOf('info', 'txtUrl', encodeURI('" + ImageFolder + ImageList.SelectedValue.Replace("'", "\\'") + "')); window.top.close(); window.top.opener.focus();"; }
protected void SelectImage(object sender, EventArgs e) { bt_DeleteImage.Enabled = (ImageList.Items.Count != 0); bt_ResizeImage.Enabled = (ImageList.Items.Count != 0); ResizeWidth.Enabled = (ImageList.Items.Count != 0); ResizeHeight.Enabled = (ImageList.Items.Count != 0); if (ImageList.Items.Count == 0) { Image1.ImageUrl = ""; ResizeWidth.Text = ""; ResizeHeight.Text = ""; return; } Image1.ImageUrl = string.Format(AttachmentDownloadURL, ImageList.SelectedValue); ATMT_AttachmentBLL att = new ATMT_AttachmentBLL(new Guid(ImageList.SelectedValue)); if (att.Model != null && att.GetData() != null) { ImageMedia img = ImageMedia.Create(att.GetData()); ResizeWidth.Text = img.Width.ToString(); ResizeHeight.Text = img.Height.ToString(); ImageAspectRatio.Value = "" + img.Width / (float)img.Height; int pos = ImageList.SelectedItem.Text.LastIndexOf('.'); if (pos == -1) { return; } bt_OkButton.OnClientClick = "window.top.opener.CKEDITOR.dialog.getCurrent().setValueOf('info', 'txtUrl', encodeURI('" + Page.ResolveUrl(Image1.ImageUrl) + "')); window.top.close(); window.top.opener.focus();"; } }
protected void Upload(object sender, EventArgs e) { if (IsImage(bt_UploadedImageFile.FileName)) { string filename = bt_UploadedImageFile.FileName; byte[] data = ImageMedia.Create(bt_UploadedImageFile.FileBytes).Resize(960, null).ToByteArray(); #region 写入新附件 ATMT_AttachmentBLL atm = new ATMT_AttachmentBLL(); atm.Model.RelateType = 75; atm.Model.Name = filename; atm.Model.ExtName = filename.Substring(filename.LastIndexOf(".") + 1).ToLower(); atm.Model.FileSize = data.Length / 1024; atm.Model.UploadUser = Session["UserName"].ToString(); atm.Model.IsDelete = "N"; int atm_id = atm.Add(data); #endregion if (atm_id > 0) { ddl_DirectoryList.SelectedIndex = 0; BindImageList(); ImageList.SelectedValue = new ATMT_AttachmentBLL(atm_id).Model.GUID.ToString(); SelectImage(null, null); } } }
/// <summary> /// Create a image object that can be interacted with from binary data. /// </summary> /// <exception cref="System.ArgumentException">If the supplied binary data is not a valid image, the ArgumentException will be thrown.</exception> public static ImageMedia Create(byte[] data) { ImageMedia result = new ImageMedia(); result._source = System.Drawing.Image.FromStream(new MemoryStream(data)); result._data = data; return(result); }
/// <summary> /// Create a image object that can be interacted with from binary data. /// </summary> /// <exception cref="System.NotSupportedException">If the supplied binary data is not a valid image, the NotSupportedException will be thrown.</exception> public static ImageMedia Create(byte[] data) { ImageMedia result = new ImageMedia(); var decoder = BitmapDecoder.Create(new MemoryStream(data), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); result.Extension = (decoder.CodecInfo.FriendlyName == "GIF Decoder" || decoder.CodecInfo.FriendlyName == "PNG Decoder") ? "png" : "jpg"; result._source = decoder.Frames[0]; result._source = BitmapDecoder.Create(new MemoryStream(data), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None).Frames[0]; result._data = data; try { result._copyright = ((BitmapMetadata)result._source.Metadata).Copyright; } catch (Exception) { } return result; }
/// <summary> /// Create a image object that can be interacted with from binary data. /// </summary> /// <exception cref="System.NotSupportedException">If the supplied binary data is not a valid image, the NotSupportedException will be thrown.</exception> public static ImageMedia Create(byte[] data) { ImageMedia result = new ImageMedia(); BitmapDecoder decoder = BitmapDecoder.Create(new MemoryStream(data), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); result.Extension = (decoder.CodecInfo.FriendlyName == "GIF Decoder" || decoder.CodecInfo.FriendlyName == "PNG Decoder") ? "png" : "jpg"; result._source = decoder.Frames[0]; result._source = BitmapDecoder.Create(new MemoryStream(data), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None).Frames[0]; result._data = data; try { result._copyright = ((BitmapMetadata)result._source.Metadata).Copyright; } catch (Exception) { } return(result); }
public async Task <IActionResult> Crop(int id, CropData args) { try { if (!ModelState.IsValid) { return(BadRequest("Invalid arguments provided to crop image.")); } BaseMedia media = await _Db.Media.FindAsync(id); if (media == null) { return(NotFound("The requested media file does not exist.")); } ImageMedia oldImage = media as ImageMedia; if (oldImage == null) { return(BadRequest("Unable to crop non-image media file.")); } // Generate new GUID string filename = Guid.NewGuid().ToString() + Path.GetExtension(oldImage.Filename); // Save the file again, passing in crop data ImageUtils.SaveImage(await System.IO.File.ReadAllBytesAsync(oldImage.FilePath), Path.Combine("Storage", "Media", "Images", filename), args); ImageMedia newImage = new ImageMedia { Title = oldImage.Title, Alt = oldImage.Alt, Name = oldImage.Name + "_cropped", // other values provided by cropping code }; await _Db.AddAsync(newImage); await _Db.SaveChangesAsync(); _Logger.LogDebug("Media file {0} cropped - new file ID is {1}", id, newImage.Id); return(Ok(newImage.Id)); // Todo: may want to pass back something else here } catch (Exception ex) { _Logger.LogError("Error cropping media file {0}: {1}", id, ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("Something went wrong, please try again later.")); } }
protected void ResizeImage(object sender, EventArgs e) { int width = Util.Parse <int>(ResizeWidth.Text); int height = Util.Parse <int>(ResizeHeight.Text); ImageMedia img = ImageMedia.Create(File.ReadAllBytes(FileImageFolder + ImageList.SelectedValue)); img.Resize(width, height); File.Delete(FileImageFolder + ImageList.SelectedValue); File.WriteAllBytes(FileImageFolder + ImageList.SelectedValue, img.ToByteArray()); ResizeMessage.Text = "Image successfully resized!"; SelectImage(null, null); }
protected void ResizeImage(object sender, EventArgs e) { int width = ResizeWidth.Text.TryParseInt(); int height = ResizeHeight.Text.TryParseInt(); ImageMedia img = ImageMedia.Create(File.ReadAllBytes(FileImageFolder + ImageList.SelectedValue)); img.Resize(width, height); File.Delete(FileImageFolder + ImageList.SelectedValue); File.WriteAllBytes(FileImageFolder + ImageList.SelectedValue, img.ToByteArray()); ResizeMessage.Text = Resource.Admin_CKEditor_ImageResized; SelectImage(null, null); }
protected void ResizeImage(object sender, EventArgs e) { ATMT_AttachmentBLL att = new ATMT_AttachmentBLL(new Guid(ImageList.SelectedValue)); int width = Util.Parse <int>(ResizeWidth.Text); int height = Util.Parse <int>(ResizeHeight.Text); ImageMedia img = ImageMedia.Create(att.GetData()); img.Resize(width, height); att.UploadFileData(img.ToByteArray()); ResizeMessage.Text = "Image successfully resized!"; SelectImage(null, null); }
protected void Upload(object sender, EventArgs e) { if (FileHelpers.CheckImageExtension(UploadedImageFile.FileName)) { string filename = UniqueFilename(UploadedImageFile.FileName); UploadedImageFile.SaveAs(FileImageFolder + filename); byte[] data = ImageMedia.Create(UploadedImageFile.FileBytes).ToByteArray(); FileStream file = File.Create(FileImageFolder + filename); file.Write(data, 0, data.Length); file.Close(); BindImageList(); ImageList.SelectedValue = filename; SelectImage(null, null); } }
// GET api/<controller> public JsonResult <int[]> Get(string path) { ImageMedia mediaImage = _sitecoreService.GetItem <ImageMedia>(path); var image = mediaImage.GetImage(); if (image == null) { return(null); } var dimens = new int[2]; if (!Int32.TryParse(image.Width.ToString(), out dimens[0]) || !Int32.TryParse(image.Height.ToString(), out dimens[1])) { return(null); } return(Json(dimens)); }
public async Task <IActionResult> Index(string filename, int width = 0, bool original = false, bool download = false) { try { if (string.IsNullOrEmpty(filename)) { return(NotFound("No filename provided")); } BaseMedia file = await _Db.Media .Where(m => m.Filename == filename) .FirstOrDefaultAsync(); if (file == null) { return(NotFound("No file exists for the supplied filename")); } // If a download is requested, set the mandatory header. if (download) { Response.Headers.Add(file.DownloadHeader()); } // Return file if not image if (file.GetCategory() != MediaCategory.Image) { //return new EmptyResult(); return(File(await System.IO.File.ReadAllBytesAsync(file.FilePath), file.MediaType.Mime)); } else { ImageMedia imageFile = (ImageMedia)file; // Return the appropriate image //return new EmptyResult(); return(File(await System.IO.File.ReadAllBytesAsync(imageFile.GetImagePath(width, original)), imageFile.MediaType.Mime)); } } catch (Exception ex) { _Logger.LogError("Error retrieving file: {0}", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("Something went wrong, please try again later.")); } }
public ActionResult imagem(HttpPostedFileBase __file) { if (__file != null) { ImageMedia _imagem = new ImageMedia(); _imagem.Imagem = new byte[__file.ContentLength]; _imagem.ImagemMimeType = __file.ContentType; __file.InputStream.Read(_imagem.Imagem, 0, __file.ContentLength); // toDo: redimensionar a imagem WebImage webimg = new WebImage(__file.InputStream); webimg.Resize(100, 100); return(RedirectToAction("Exibir", new { _imagem.Id })); } return(View()); }
public string ResizeImage(CKEditorModel model) { _modObj = model; _modObj.ImageFolder = (model.DirectoryList == "Root" ? "" : "\\" + model.DirectoryList); _modObj.ImageURL = _modObj.ImageFolder + "\\" + _modObj.ImageList; int width = Util.Parse <int>(_modObj.ResizeWidth); int height = Util.Parse <int>(_modObj.ResizeHeight); ImageMedia img = ImageMedia.Create(System.IO.File.ReadAllBytes(_modObj.ImageURL)); img.Resize(width, height); System.IO.File.Delete(_modObj.ImageURL); System.IO.File.WriteAllBytes(_modObj.ImageURL, img.ToByteArray()); return("true"); }
public ActionResult GetImageDetail(string id, string ImageList) { _modObj.DirectoryList = id; _modObj.ImageFolder = (id == "Root" ? "" : "\\" + id); _modObj.ImageURL = _modObj.ImageFolder + "\\" + ImageList; _modObj.ImageHttpPath = _modObj.ImageContentURL + (id == "Root" ? "" : id + "/") + ImageList; ImageMedia img = ImageMedia.Create(System.IO.File.ReadAllBytes(_modObj.ImageURL)); _modObj.ResizeWidth = img.Width.ToString(); _modObj.ResizeHeight = img.Height.ToString(); _modObj.ImageAspectRatio = "" + img.Width / (float)img.Height; JsonResult jResult = new JsonResult(); jResult.Data = _modObj; return(jResult); }
public async Task <IActionResult> GetOne(int id) { try { BaseMedia mediaFile = await _Db.Media.FindAsync(id); ImageMedia imageFile = mediaFile as ImageMedia; AudioMedia audioFile = mediaFile as AudioMedia; if (mediaFile == null) { return(NotFound("No file exists for the supplied ID")); } return(Ok(new { mediaFile.Id, mediaFile.Name, mediaFile.FilePath, mediaFile.Size, mediaFile.MediaType, Source = new { showCopyright = mediaFile.ShowCopyright, info = mediaFile.Source }, fileName = mediaFile.Filename, height = imageFile?.Height, width = imageFile?.Width, versions = imageFile?.Versions, title = imageFile?.Title, alt = imageFile?.Alt, duration = audioFile?.Duration, tags = mediaFile.Tags(), usages = mediaFile.GetUsages(_Db) })); } catch (Exception ex) { _Logger.LogError("Error retrieving file data: {0}", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("Something went wrong, please try again later.")); } }
protected void SelectImage(object sender, EventArgs e) { RenameImageButton.Enabled = (ImageList.Items.Count != 0); DeleteImageButton.Enabled = (ImageList.Items.Count != 0); ResizeImageButton.Enabled = (ImageList.Items.Count != 0); ResizeWidth.Enabled = (ImageList.Items.Count != 0); ResizeHeight.Enabled = (ImageList.Items.Count != 0); if (ImageList.Items.Count == 0) { Image1.ImageUrl = ""; ResizeWidth.Text = ""; ResizeHeight.Text = ""; return; } Image1.ImageUrl = ImageFolder + ImageList.SelectedValue + "?" + new Random().Next(1000); ImageMedia img = ImageMedia.Create(File.ReadAllBytes(FileImageFolder + ImageList.SelectedValue)); ResizeWidth.Text = img.Width.ToString(CultureInfo.InvariantCulture); ResizeHeight.Text = img.Height.ToString(CultureInfo.InvariantCulture); ImageAspectRatio.Value = (img.Width / (float)img.Height).ToString(CultureInfo.InvariantCulture); int pos = ImageList.SelectedItem.Text.LastIndexOf('.'); if (pos == -1) { return; } RenameImageButton.OnClientClick = string.Format( "var name = prompt('{0}:','{1}'); if (name == null || name == '') return false; $('#{2}').val(name + '{3}');", Resource.Admin_CKEditor_EnterFileName, ImageList.SelectedItem.Text.Substring(0, pos), NewImageName.ClientID, ImageList.SelectedItem.Text.Substring(pos)); OkButton.OnClientClick = string.Format( "window.top.opener.CKEDITOR.dialog.getCurrent().setValueOf('info', 'txtUrl', encodeURI('{0}{1}')); window.top.close(); window.top.opener.focus();", ImageFolder, ImageList.SelectedValue.Replace("'", "\\'")); }
public async Task <IActionResult> Index(IFormCollection request) { try { // Create required directories if not existing EnsureInit(); // Deserialize cropping data if applicable CropData cropData = null; if (request.Str("cropData") != null) { cropData = JsonConvert.DeserializeObject <CropData>(request.Str("cropData")); } // Original filename string uploadedName = request.Str("filename"); // Generate a backend filename for the uploaded file - same extension as uploaded file. string filename = Guid.NewGuid().ToString() + Path.GetExtension(uploadedName); string fileType = request.Str("fileType"); // Determine what type of file has been uploaded and act accordingly (may want to refactor these) // FOR IMAGES if (MediaType.MimesForCategory(MediaCategory.Image).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Images", filename); // Save image and all associated versions of it. var filedata = ImageUtils.SaveImage(request.Str("file") .Split(',')[1], filepath, cropData); // Create database record to track images ImageMedia dbImageMedia = new ImageMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = filedata["size"], Title = request.Str("title"), Alt = request.Str("alt"), Width = filedata["width"], Height = filedata["height"], Versions = filedata["versions"] }; await _Db.AddAsync(dbImageMedia); } // FOR AUDIO else if (MediaType.MimesForCategory(MediaCategory.Audio).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Audio", filename); // Save the audio file byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes(); await System.IO.File.WriteAllBytesAsync(filepath, bytes); // Read the audio file to determine its duration - it will either be mp3(mpeg) or wav // Configure ffprobe path using appsettings values FFProbe probe = new FFProbe(); probe.ToolPath = _Config["ffprobePath"]; // If running linux, look for ffprobe instaed of ffprobe.exe if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { probe.FFProbeExeName = "ffprobe"; } // Get audio file metadata MediaInfo mediaInfo = probe.GetMediaInfo(Path.Combine(_HostingEnv.ContentRootPath, filepath)); // Create the media database record AudioMedia audioMedia = new AudioMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = new FileInfo(filepath).Length, Duration = Math.Round(mediaInfo.Duration.TotalSeconds) }; await _Db.AddAsync(audioMedia); } // FOR GENERAL else if (MediaType.MimesForCategory(MediaCategory.General).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Documents", filename); // Save the file byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes(); System.IO.File.WriteAllBytes(filepath, bytes); // Create the media database record GeneralMedia generalMedia = new GeneralMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = new FileInfo(filepath).Length, }; await _Db.AddAsync(generalMedia); } else { return(new UnsupportedMediaTypeResult()); } await _Db.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error uploading file: {0}", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please contact the devloper if the problem persists", ex.Message))); } }