public UploadProfilePictureOutput UploadProfilePicture() { try { var profilePictureFile = Request.Form.Files.First(); //Check input if (profilePictureFile == null) { throw new UserFriendlyException(L("ProfilePicture_Change_Error")); } if (profilePictureFile.Length > MaxProfilePictureSize) { throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit", AppConsts.MaxProfilPictureBytesUserFriendlyValue)); } byte[] fileBytes; using (var stream = profilePictureFile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception("Uploaded file is not an accepted image file !"); } //Delete old temp profile pictures AppFileHelper.DeleteFilesInFolderIfExists(_appFolders.TempFileDownloadFolder, "userProfileImage_" + AbpSession.GetUserId()); //Save new picture var fileInfo = new FileInfo(profilePictureFile.FileName); string ext = fileInfo.Extension.ToLower().Trim(); if (ext.Equals(".jpg") || ext.Equals(".png") || ext.Equals(".gif") || ext.Equals(".jpeg")) { var tempFileName = "userProfileImage_" + AbpSession.GetUserId() + fileInfo.Extension; var tempFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, tempFileName); System.IO.File.WriteAllBytes(tempFilePath, fileBytes); using (var bmpImage = new Bitmap(tempFilePath)) { return(new UploadProfilePictureOutput { FileName = tempFileName, Width = bmpImage.Width, Height = bmpImage.Height }); } } else { throw new UserFriendlyException("Uploaded file format is not correct !"); } } catch (Exception ex) { return(new UploadProfilePictureOutput(new ErrorInfo(ex.Message))); } }
public virtual Task <FileUploadOutputDto> CreateAsync(FileUploadInputDto input) { if (input.Bytes.IsNullOrEmpty()) { ThrowValidationException("Bytes can not be null or empty!", "Bytes"); } if (input.Bytes.Length > BloggingWebConsts.FileUploading.MaxFileSize) { throw new UserFriendlyException($"File exceeds the maximum upload size ({BloggingWebConsts.FileUploading.MaxFileSizeAsMegabytes} MB)!"); } if (!ImageFormatHelper.IsValidImage(input.Bytes, FileUploadConsts.AllowedImageUploadFormats)) { throw new UserFriendlyException("Not a valid image format!"); } var uniqueFileName = GenerateUniqueFileName(Path.GetExtension(input.Name)); var filePath = Path.Combine(Options.FileUploadLocalFolder, uniqueFileName); if (!Directory.Exists(Options.FileUploadLocalFolder)) { Directory.CreateDirectory(Options.FileUploadLocalFolder); } File.WriteAllBytes(filePath, input.Bytes); //TODO: Previously was using WriteAllBytesAsync, but it's only in .netcore. return(Task.FromResult(new FileUploadOutputDto { Name = uniqueFileName, WebUrl = "/api/blogging/files/www/" + uniqueFileName })); }
/// <summary> /// 上传图片文件并上传至微信 /// </summary> /// <returns></returns> public async Task <JsonResult> UploadMatialPic() { try { var profilePictureFile = Request.Form.Files.First(); //Check input if (profilePictureFile == null) { throw new UserFriendlyException(L("ProfilePicture_Change_Error")); } if (profilePictureFile.Length > 2097152) //2MB. { throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit")); } byte[] fileBytes; using (var stream = profilePictureFile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception("上传文件非图片文件"); } //Delete old temp profile pictures AppFileHelper.DeleteFilesInFolderIfExists(_appFolders.TempFileDownloadFolder, "martialPic_" + AbpSession.GetUserId()); //Save new picture var fileInfo = new FileInfo(profilePictureFile.FileName); var tempFileName = "martialPic_" + AbpSession.GetUserId() + Guid.NewGuid().ToString() + fileInfo.Extension; var tempFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, tempFileName); await System.IO.File.WriteAllBytesAsync(tempFilePath, fileBytes); var virtualPath = _matialFileService.MatialFileTempPath + tempFileName; var mediaId = ""; try { mediaId = await _wxMediaAppService.UploadMedia(tempFilePath, "");//上传至微信 } catch (Exception e) { Logger.Error("上传微信错误,错误信息:" + e.Message + ";错误堆栈:" + e.StackTrace); } //var mediaId = "测试"; return(Json(new AjaxResponse(new { fileName = tempFileName, fileFullPath = tempFilePath, fileVirtualPath = virtualPath, mediaID = mediaId }))); } catch (UserFriendlyException ex) { return(Json(new AjaxResponse(new ErrorInfo(ex.Message)))); } }
protected override FilterContext CreateFilterContext(ProcessingPipelineContext context) { IImageFormat targetFormat = null; if (context.ImageWizardOptions.UseAcceptHeader) { //try to use mime type from accept header targetFormat = ImageFormatHelper.FirstOrDefault(context.AcceptMimeTypes); } if (targetFormat == null) { //use mime type of the original image targetFormat = ImageFormatHelper.FirstOrDefault(context.Result.MimeType); } SKBitmap bitmap = SKBitmap.Decode(context.Result.Data); if (context.ImageWizardOptions.UseClintHints) { if (context.ClientHints.DPR != null) { string method = $"dpr({context.ClientHints.DPR.Value.ToString("0.0", CultureInfo.InvariantCulture)})"; //url_filters.Insert(0, method); } } return(new SkiaSharpFilterContext(context, bitmap, targetFormat)); }
public async Task UploadAsync(long groupId) { var profilePictureFile = _contextAccessor.HttpContext.Request.Form.Files.First(); //Check input if (profilePictureFile == null) { throw new UserFriendlyException(L("ProfilePicture_Change_Error")); } if (profilePictureFile.Length > 1048576) //1MB. { throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit")); } byte[] fileBytes; using (var stream = profilePictureFile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception("Uploaded file is not an accepted image file !"); } await _pictureManager.UploadPictureAsync(fileBytes, profilePictureFile.FileName, groupId); }
/// <summary> /// Configure device and report frame format that will be used during streaming. /// This method must return a proper ImageDescriptor so we can pre-allocate buffers. /// </summary> public ImageDescriptor Prepare() { Open(); if (device == null || featureControl == null) { return(ImageDescriptor.Invalid); } firstOpen = false; resultingFramerate = (float)DahengHelper.GetResultingFramerate(device); width = (int)featureControl.GetIntFeature("Width").GetValue(); height = (int)featureControl.GetIntFeature("Height").GetValue(); isColor = DahengHelper.IsColor(featureControl); ImageFormat format = ImageFormat.RGB24; incomingBufferSize = ImageFormatHelper.ComputeBufferSize(width, height, format); incomingBuffer = new byte[incomingBufferSize]; int outgoingBufferSize = ImageFormatHelper.ComputeBufferSize(width, height, format); bool topDown = false; return(new ImageDescriptor(format, width, height, topDown, outgoingBufferSize)); }
/// <summary> /// In case of configure failure, we would have retrieved a single image and the corresponding image descriptor. /// A limitation of the single snapshot retriever is that the format is always RGB24, even though the grabber may /// use a different format. /// </summary> public ImageDescriptor GetPrepareFailedImageDescriptor(ImageDescriptor input) { frameBufferSize = ImageFormatHelper.ComputeBufferSize(input.Width, input.Height, input.Format); frameBuffer = new byte[frameBufferSize]; return(input); }
public static void ValidateImage([CanBeNull] this IFormFile file, out byte[] fileBytes) { fileBytes = null; if (file == null) { throw new UserFriendlyException("No file found!"); } if (file.Length <= 0) { throw new UserFriendlyException("File is empty!"); } if (!file.ContentType.Contains("image")) { throw new UserFriendlyException("Not a valid image!"); } using (var stream = file.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.IsValidImage(fileBytes, BloggingWebConsts.FileUploading.AllowedImageUploadFormats)) { throw new UserFriendlyException("Not a valid image format!"); } if (file.Length > BloggingWebConsts.FileUploading.MaxFileSize) { throw new UserFriendlyException($"File exceeds the maximum upload size ({BloggingWebConsts.FileUploading.MaxFileSizeAsMegabytes} MB)!"); } }
public virtual async Task <FileUploadOutputDto> CreateAsync(FileUploadInputDto input) { if (input.Bytes.IsNullOrEmpty()) { ThrowValidationException("Bytes of file can not be null or empty!", "Bytes"); } if (input.Bytes.Length > BloggingWebConsts.FileUploading.MaxFileSize) { throw new UserFriendlyException($"File exceeds the maximum upload size ({BloggingWebConsts.FileUploading.MaxFileSizeAsMegabytes} MB)!"); } if (!ImageFormatHelper.IsValidImage(input.Bytes, FileUploadConsts.AllowedImageUploadFormats)) { throw new UserFriendlyException("Invalid image format!"); } var uniqueFileName = GenerateUniqueFileName(Path.GetExtension(input.Name)); await BlobContainer.SaveAsync(uniqueFileName, input.Bytes); return(new FileUploadOutputDto { Name = uniqueFileName, WebUrl = "/api/blogging/files/www/" + uniqueFileName }); }
public UploadServiceImagesOutput UploadServiceImages(FileDto input) { try { var profilePictureFile = Request.Form.Files.First(); byte[] fileBytes; using (var stream = profilePictureFile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception(L("IncorrectImageFormat")); } _tempFileCacheManager.SetFile(input.FileToken, fileBytes); using (var bmpImage = new Bitmap(new MemoryStream(fileBytes))) { return(new UploadServiceImagesOutput { FileToken = input.FileToken, FileName = input.FileName, FileType = input.FileType, Width = bmpImage.Width, Height = bmpImage.Height }); } } catch (UserFriendlyException ex) { return(new UploadServiceImagesOutput(new ErrorInfo(ex.Message))); } }
public async Task <ActionResult> UploadProfile() { var profile = Request.Form.Files.First(); if (profile == null) { throw new Exception("Uploaded file is Empty !"); } if (!Directory.Exists(_appFolders.TempFileDownloadFolder)) { Directory.CreateDirectory(_appFolders.TempFileDownloadFolder); } byte[] fileBytes; using (var stream = profile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception("Uploaded file is not an accepted image file !"); } //Delete old temp profile pictures AppFileHelper.DeleteFilesInFolderIfExists(_appFolders.TempFileDownloadFolder, "userProfileImage_" + AbpSession.GetUserId()); //Save new picture var fileInfo = new FileInfo(profile.FileName); var tempFileName = "userProfileImage_" + AbpSession.GetUserId() + fileInfo.Extension; var tempFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, tempFileName); await System.IO.File.WriteAllBytesAsync(tempFilePath, fileBytes); return(new JsonResult(tempFileName)); }
public virtual async Task <FileUploadOutputDto> CreateAsync(FileUploadInputDto input) { if (input.File == null) { ThrowValidationException("Bytes of file can not be null or empty!", nameof(input.File)); } if (input.File.ContentLength > BloggingWebConsts.FileUploading.MaxFileSize) { throw new UserFriendlyException($"File exceeds the maximum upload size ({BloggingWebConsts.FileUploading.MaxFileSizeAsMegabytes} MB)!"); } var position = input.File.GetStream().Position; if (!ImageFormatHelper.IsValidImage(input.File.GetStream(), FileUploadConsts.AllowedImageUploadFormats)) { throw new UserFriendlyException("Invalid image format!"); } // IsValidImage may change the position of the stream if (input.File.GetStream().CanSeek) { input.File.GetStream().Position = position; } var uniqueFileName = GenerateUniqueFileName(Path.GetExtension(input.Name)); await BlobContainer.SaveAsync(uniqueFileName, input.File.GetStream()); return(new FileUploadOutputDto { Name = uniqueFileName, WebUrl = "/api/blogging/files/www/" + uniqueFileName }); }
private unsafe void FillRGB24(IntPtr buffer) { image = new Bitmap(width, height, PixelFormat.Format24bppRgb); Rectangle rect = new Rectangle(0, 0, width, height); BitmapData bmpData = null; try { bmpData = image.LockBits(rect, ImageLockMode.WriteOnly, image.PixelFormat); IntPtr[] ptrBmp = new IntPtr[] { bmpData.Scan0 }; int stride = rect.Width * 3; NativeMethods.memcpy(bmpData.Scan0.ToPointer(), buffer.ToPointer(), stride * height); int bufferSize = ImageFormatHelper.ComputeBufferSize(width, height, Video.ImageFormat.RGB24); imageDescriptor = new ImageDescriptor(Video.ImageFormat.RGB24, image.Width, image.Height, true, bufferSize); } catch (Exception e) { log.ErrorFormat("Error while copying bitmaps. {0}", e.Message); } finally { if (bmpData != null) { image.UnlockBits(bmpData); } } }
protected override FilterContext CreateFilterContext(ProcessingPipelineContext context) { Image image = Image.Load(context.Result.Data); IImageFormat targetFormat = ImageFormatHelper.Parse(context.Result.MimeType); return(new ImageSharpFilterContext(context, image, targetFormat, context.ClientHints)); }
protected override FilterContext CreateFilterContext(ProcessingPipelineContext context) { IImageFormat targetFormat = ImageFormatHelper.Parse(context.Result.MimeType); SKBitmap bitmap = SKBitmap.Decode(context.Result.Data); return(new SkiaSharpFilterContext(context, bitmap, targetFormat, context.ClientHints)); }
private int section; // The section of rows we are in, for waterfall overlap. /// <summary> /// Compute the new image size/framerate and prepare the buffers. /// </summary> public void Prepare(int width, int height, ImageFormat format, float inputFramerate) { thresholdHeight = PreferencesManager.CapturePreferences.PhotofinishConfiguration.ThresholdHeight; enabled = height <= thresholdHeight; if (!enabled) { return; } // Constraints: // -The number of consolidated rows has to be lower than the height threshold, otherwise we won't have enough source material to copy. // -The output height has to be a multiple of the number of consolidated rows, otherwise there will be a hole at the bottom of the output. consolidationHeight = PreferencesManager.CapturePreferences.PhotofinishConfiguration.ConsolidationHeight; consolidationHeight = Math.Min(consolidationHeight, thresholdHeight); outputHeight = PreferencesManager.CapturePreferences.PhotofinishConfiguration.OutputHeight; outputHeight = outputHeight - (outputHeight % consolidationHeight); waterfallEnabled = PreferencesManager.CapturePreferences.PhotofinishConfiguration.Waterfall; if (waterfallEnabled) { waterfallFlushHeight = PreferencesManager.CapturePreferences.PhotofinishConfiguration.WaterfallFlushHeight; bool isWaterfallFlushHeightValid = waterfallFlushHeight >= consolidationHeight && waterfallFlushHeight <= outputHeight && (outputHeight % waterfallFlushHeight == 0) && (waterfallFlushHeight % consolidationHeight == 0); if (!isWaterfallFlushHeightValid) { waterfallFlushHeight = outputHeight; } } // Prepare buffer for output images. float rowsPerSecond = inputFramerate * consolidationHeight; if (waterfallEnabled) { this.resultingFramerate = rowsPerSecond / waterfallFlushHeight; } else { this.resultingFramerate = rowsPerSecond / outputHeight; } int pfBufferSize = ImageFormatHelper.ComputeBufferSize(width, outputHeight, format); imageDescriptor = new ImageDescriptor(format, width, outputHeight, true, pfBufferSize); bufferCurrent = new byte[pfBufferSize]; bufferOld = new byte[pfBufferSize]; bufferOutput = new byte[pfBufferSize]; row = 0; }
/// <summary> /// Consolidate the incoming rows. /// Returns true if the buffer has to be flushed, in which case the properties BufferOutput will be valid /// and can be used by the caller to raise the FrameProducedEvent. /// </summary> public bool Consolidate(byte[] buffer) { if (!enabled) { throw new InvalidOperationException(); } bool flush = false; int bytesPerPixel = ImageFormatHelper.BytesPerPixel(imageDescriptor.Format); int stride = imageDescriptor.Width * bytesPerPixel; // Consolidate the current sub-frame. Buffer.BlockCopy(buffer, 0, bufferCurrent, row * imageDescriptor.Width * bytesPerPixel, imageDescriptor.Width * bytesPerPixel * consolidationHeight); row += consolidationHeight; if (waterfallEnabled && (row % waterfallFlushHeight == 0)) { // Flush the current and old image to output in sliding window mode. // "section" is at 0 after we grabbed the first section of rows. int totalSections = outputHeight / waterfallFlushHeight; // Rows are always added to the bottom, so here we continue this pattern. // The current image is copied at the bottom, and the old image is copied at the top. // We just need to figure out which portion of each image to copy. int bufferCurrentSource = 0; int bufferCurrentLength = (section + 1) * waterfallFlushHeight * stride; int bufferCurrentDestination = (totalSections - (section + 1)) * waterfallFlushHeight * stride; int bufferOldSource = bufferCurrentLength; int bufferOldLength = bufferCurrentDestination; int bufferOldDestination = 0; Buffer.BlockCopy(bufferCurrent, bufferCurrentSource, bufferOutput, bufferCurrentDestination, bufferCurrentLength); Buffer.BlockCopy(bufferOld, bufferOldSource, bufferOutput, bufferOldDestination, bufferOldLength); section = (section + 1) % totalSections; flush = true; } if (row >= outputHeight) { row = 0; section = 0; if (!waterfallEnabled) { flush = true; } // Swap buffers. byte[] pfBufferTemp = bufferOld; bufferOld = bufferCurrent; bufferCurrent = bufferOld; } return(flush); }
/// <summary> /// Configure device and report frame format that will be used during streaming. /// This method must return a proper ImageDescriptor so we can pre-allocate buffers. /// </summary> public ImageDescriptor Prepare() { Open(); if (deviceHandle == null || !deviceHandle.IsValid) { return(ImageDescriptor.Invalid); } firstOpen = false; // Get the configured framerate for recording support. if (Pylon.DeviceFeatureIsReadable(deviceHandle, "ResultingFrameRateAbs")) { resultingFramerate = (float)Pylon.DeviceGetFloatFeature(deviceHandle, "ResultingFrameRateAbs"); } else if (Pylon.DeviceFeatureIsReadable(deviceHandle, "ResultingFrameRate")) { resultingFramerate = (float)Pylon.DeviceGetFloatFeature(deviceHandle, "ResultingFrameRate"); } SpecificInfo specific = summary.Specific as SpecificInfo; string streamFormatSymbol = specific.StreamFormat; bool hasWidth = Pylon.DeviceFeatureIsReadable(deviceHandle, "Width"); bool hasHeight = Pylon.DeviceFeatureIsReadable(deviceHandle, "Height"); bool hasPixelFormat = Pylon.DeviceFeatureIsReadable(deviceHandle, "PixelFormat"); bool canComputeImageDescriptor = hasWidth && hasHeight && hasPixelFormat; if (!canComputeImageDescriptor) { return(ImageDescriptor.Invalid); } int width = (int)Pylon.DeviceGetIntegerFeature(deviceHandle, "Width"); int height = (int)Pylon.DeviceGetIntegerFeature(deviceHandle, "Height"); string pixelFormat = Pylon.DeviceFeatureToString(deviceHandle, "PixelFormat"); // Note: the image provider will perform the Bayer conversion itself and only output two formats. // - Y800 for anything monochrome. // - RGB32 for anything color. EPylonPixelType pixelType = Pylon.PixelTypeFromString(pixelFormat); if (pixelType == EPylonPixelType.PixelType_Undefined) { return(ImageDescriptor.Invalid); } bool monochrome = Pylon.IsMono(pixelType) && !Pylon.IsBayer(pixelType); ImageFormat format = monochrome ? format = ImageFormat.Y800 : ImageFormat.RGB32; int bufferSize = ImageFormatHelper.ComputeBufferSize(width, height, format); bool topDown = true; return(new ImageDescriptor(format, width, height, topDown, bufferSize)); }
public ActionResult AddPost(Post model, HttpPostedFileBase imageData) { if (!ModelState.IsValid) { var posts1 = dBContext.Posts.OrderByDescending(c => c.Id).ToList(); ViewBag.Posts = posts1; return(View("Index", model)); } if (imageData == null && model.Text == null) { ModelState.AddModelError(string.Empty, "Не загружено изображение или отсутствует текст"); var posts1 = dBContext.Posts.OrderByDescending(c => c.Id).ToList(); ViewBag.Posts = posts1; return(View("Index", model)); } model.PublishDate = DateTime.Now; if (imageData != null) { if (!ImageFormatHelper.IsJpg(imageData)) { ModelState.AddModelError(string.Empty, "Загруженное изображение не картинка формата JPG"); var postsdb = dBContext.Posts.OrderByDescending(c => c.Id).ToList(); ViewBag.Posts = postsdb; return(View("Index", model)); } model.Photo = ImageSaveHelper.SaveImage(imageData); } var userId = Convert.ToInt32(Session["UserId"]); var userInDb = dBContext.Users.FirstOrDefault(c => c.Id == userId); if (userInDb == null) { TempData["errorMessage"] = "Время сессии истекло. Авторизуйетсь повторно!"; return(RedirectToAction("Index", "Home")); } model.Author = userInDb; dBContext.Posts.Add(model); dBContext.SaveChanges(); var posts = dBContext.Posts.OrderByDescending(c => c.Id).ToList(); ViewBag.Posts = posts; ModelState.Clear(); return(View("Index")); }
private static Tuple <byte[], ImageFormat> QuadrasizeImage(byte[] adImage) { Image image = ImageHelper.ByteArrayToImage(adImage); Image newImage = ImageHelper.QuadrasizeImage(image); byte[] tfsImage = ImageHelper.ImageToByteArray(newImage, System.Drawing.Imaging.ImageFormat.Png); ImageFormat tfsImageFormat = ImageFormatHelper.GetImageFormat(tfsImage); return(Tuple.Create(tfsImage, tfsImageFormat)); }
public JsonResult UploadProductSubGroupPicture(int ProductSubGroupId, string ImgPath) { try { var productSubGroupPictureFile = Request.Form.Files.First(); //Check input if (productSubGroupPictureFile == null) { throw new UserFriendlyException(L("ProductSubGroupPicture_Change_Error")); } if (productSubGroupPictureFile.Length > 1048576) //1MB. { throw new UserFriendlyException(L("ProductSubGroupPicture_Warn_SizeLimit")); } byte[] fileBytes; using (var stream = productSubGroupPictureFile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception("Uploaded file is not an accepted image file !"); } var ProductSubGroup = _appFolders.ProductSubGroupFilePath; if (!Directory.Exists(ProductSubGroup)) { Directory.CreateDirectory(ProductSubGroup); } //Delete old ProductSubGroup pictures AppFileHelper.DeleteFilesInFolderIfExists(_appFolders.FindFilePath, ImgPath); //Save new picture var fileInfo = new FileInfo(productSubGroupPictureFile.FileName); var tempFileName = productSubGroupPictureFile.FileName + fileInfo.Extension; var tempFilePath = Path.Combine(ProductSubGroup, tempFileName); System.IO.File.WriteAllBytes(tempFilePath, fileBytes); using (var bmpImage = new Bitmap(tempFilePath)) { return(Json(new AjaxResponse(new { fileName = "Common/Images/ProductSubGroup/" + tempFileName, width = bmpImage.Width, height = bmpImage.Height }))); } } catch (UserFriendlyException ex) { return(Json(new AjaxResponse(new ErrorInfo(ex.Message)))); } }
private void camera_EventFrame(object sender, EventArgs e) { uEye.Camera camera = sender as uEye.Camera; if (camera == null || !camera.IsOpened) { waitHandle.Set(); return; } uEye.Defines.DisplayMode mode; camera.Display.Mode.Get(out mode); if (mode != uEye.Defines.DisplayMode.DiB) { waitHandle.Set(); return; } Int32 s32MemID; camera.Memory.GetActive(out s32MemID); camera.Memory.Lock(s32MemID); Bitmap bitmap; camera.Memory.ToBitmap(s32MemID, out bitmap); if (bitmap != null) { if (image != null) { image.Dispose(); } // Force output into an RGB24 bitmap. image = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb); Rectangle rect = new Rectangle(0, 0, image.Width, image.Height); using (Graphics g = Graphics.FromImage(image)) { g.DrawImage(bitmap, Point.Empty); } int bufferSize = ImageFormatHelper.ComputeBufferSize(image.Width, image.Height, Kinovea.Services.ImageFormat.RGB24); imageDescriptor = new ImageDescriptor(Kinovea.Services.ImageFormat.RGB24, image.Width, image.Height, true, bufferSize); bitmap.Dispose(); } camera.Memory.Unlock(s32MemID); waitHandle.Set(); }
public JsonResult UploadMultiTempProductPicture(int TempProductId) { try { var TempProductPictureFile = Request.Form.Files.First(); //Check input if (TempProductPictureFile == null) { throw new UserFriendlyException(L("ProductPicture_Change_Error")); } if (TempProductPictureFile.Length > 1048576) //1MB. { throw new UserFriendlyException(L("ProductPicture_Warn_SizeLimit")); } byte[] fileBytes; using (var stream = TempProductPictureFile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception("Uploaded file is not an accepted image file !"); } var TempProducts = _appFolders.TempProductFilePath + @"\" + TempProductId; if (!Directory.Exists(TempProducts)) { Directory.CreateDirectory(TempProducts); } //Delete old temp product pictures AppFileHelper.DeleteFilesInFolderIfExists(TempProducts, TempProductPictureFile.FileName); //Save new picture var fileInfo = new FileInfo(TempProductPictureFile.FileName); var tempFileName = TempProductPictureFile.FileName; var tempFilePath = Path.Combine(TempProducts, tempFileName); System.IO.File.WriteAllBytes(tempFilePath, fileBytes); using (var bmpImage = new Bitmap(tempFilePath)) { return(Json(new AjaxResponse(new { fileName = "Common/Images/TemporaryProduct/" + TempProductId + "/" + tempFileName, width = bmpImage.Width, height = bmpImage.Height }))); } } catch (UserFriendlyException ex) { return(Json(new AjaxResponse(new ErrorInfo(ex.Message)))); } }
public ActionResult Register(User model, HttpPostedFileBase imageData) { if (ModelState.IsValid) { //регистрация if (model.Password != model.PasswordConfirm) { ModelState.AddModelError(string.Empty, "Введенные пароли не совпадают!"); return(View("Index", model)); } var userInDb = dBContext.Users.FirstOrDefault(c => c.Nickname == model.Nickname); if (userInDb != null) { ModelState.AddModelError(string.Empty, "Пользователь с таким псевдонимом уже существует!"); return(View("Index", model)); } var userEmailInDb = dBContext.Users.FirstOrDefault(c => c.Email == model.Email); if (userEmailInDb != null) { ModelState.AddModelError(string.Empty, "Данный адрес электронной почты уже использован!"); return(View("Index", model)); } if (imageData != null) { if (!ImageFormatHelper.IsJpg(imageData)) { ModelState.AddModelError(string.Empty, "Загруженное изображение не картинка формата JPG"); return(View("Index", model)); } model.Photo = ImageSaveHelper.SaveImage(imageData); } dBContext.Users.Add(model); dBContext.SaveChanges(); FormsAuthentication.SetAuthCookie(model.Nickname, false); Session["UserId"] = model.Id.ToString(); Session["Nickname"] = model.Nickname; // Session["Photo"] = userInDb.Photo.ToString(); Session["Photo"] = ImageUrlHelper.GetUrl(model.Photo); return(RedirectToAction("Index", "Feed")); } return(View("Index", model)); }
public static (FormatId id, EncodeFlags flags) ParseFormat(string text) { if (text is null) { throw new ArgumentNullException(nameof(text)); } switch (text.ToLower()) { case "apng": return(Apng, default); case "png": return(Png, default); case "jpeg": return(Jpeg, default); case "gif": return(Gif, default); case "webp": return(WebP, default); case "ico": return(Ico, default); // audio case "aac": return(Aac, default); case "flac": return(Flac, default); case "m4a": return(M4a, default); case "mp3": return(Mp3, default); case "opus": return(Opus, default); // videos case "webm": return(WebM, default); case "mp4": return(Mp4, default); case "pjpg": return(Jpeg, EncodeFlags.Progressive); case "png8": return(Png, EncodeFlags._8bit); case "png32": return(Png, EncodeFlags._32bit); case "webpll": return(WebP, EncodeFlags.Lossless); case "webply": return(WebP, default); default: return((FormatId)ImageFormatHelper.Parse(text), default); } }
private void Device_NewFrame(object sender, NewFrameEventArgs e) { image = new Bitmap(e.Frame.Width, e.Frame.Height, e.Frame.PixelFormat); using (Graphics g = Graphics.FromImage(image)) { g.DrawImageUnscaled(e.Frame, Point.Empty); } int bufferSize = ImageFormatHelper.ComputeBufferSize(image.Width, image.Height, Video.ImageFormat.RGB24); imageDescriptor = new ImageDescriptor(Video.ImageFormat.RGB24, image.Width, image.Height, true, bufferSize); waitHandle.Set(); }
/// <summary> /// Configure device and report frame format that will be used during streaming. /// This method must return a proper ImageDescriptor so we can pre-allocate buffers. /// </summary> public ImageDescriptor Prepare() { ConfigureDevice(); AForge.Video.DirectShow.VideoCapabilities cap = null; if (device.VideoResolution == null) { // This device was never connected to in Kinovea, use the first media type. AForge.Video.DirectShow.VideoCapabilities[] caps = device.VideoCapabilities; if (caps.Length == 0) { log.ErrorFormat("Cannot get any media type for the device."); return(ImageDescriptor.Invalid); } cap = caps[0]; device.SetMediaTypeAndFramerate(cap.Index, (float)cap.AverageFrameRate); log.DebugFormat("Device set to default configuration: Index:{0}. ({1}x{2} @ {3:0.###} fps ({4})).", cap.Index, cap.FrameSize.Width, cap.FrameSize.Height, cap.AverageFrameRate, cap.Compression); } else { cap = device.VideoResolution; } int width = cap.FrameSize.Width; int height = cap.FrameSize.Height; resultingFramerate = cap.AverageFrameRate; ImageFormat format = ImageFormat.RGB24; switch (cap.Compression) { case "RGB24": default: format = ImageFormat.RGB24; break; case "MJPG": format = ImageFormat.JPEG; break; } int bufferSize = ImageFormatHelper.ComputeBufferSize(width, height, format); bool topDown = false; return(new ImageDescriptor(format, width, height, topDown, bufferSize)); }
public UploadProfilePictureOutputDto UploadProfilePicture(FileDto input) { try { var profilePictureFile = Request.Form.Files.First(); //Check input if (profilePictureFile == null) { throw new UserFriendlyException(L("ProfilePicture_Change_Error")); } //上传的图片超过大小限制 if (profilePictureFile.Length > MaxProfilePictureSize) { throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit", AppConsts.MaxProfilePictureBytesUserFriendlyValue)); } byte[] fileBytes; using (var stream = profilePictureFile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception("请上传图片文件,仅接受Jpg、PNG、Gif三种格式!"); } _dataTempFileCacheManager.SetFile(input.FileToken, fileBytes); using (var bmpImage = new Bitmap(new MemoryStream(fileBytes))) { return(new UploadProfilePictureOutputDto { FileToken = input.FileToken, FileName = input.FileName, FileType = input.FileType, Width = bmpImage.Width, Height = bmpImage.Height }); } } catch (UserFriendlyException ex) { return(new UploadProfilePictureOutputDto(new ErrorInfo(ex.Message))); } }
public JsonResult UploadProfilePicture() { try { var profilePictureFile = Request.Form.Files.First(); //Check input if (profilePictureFile == null) { throw new UserFriendlyException(L("ProfilePicture_Change_Error")); } if (profilePictureFile.Length > 1048576) //1MB. { throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit")); } byte[] fileBytes; using (var stream = profilePictureFile.OpenReadStream()) { fileBytes = stream.GetAllBytes(); } if (!ImageFormatHelper.GetRawImageFormat(fileBytes).IsIn(ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif)) { throw new Exception("Uploaded file is not an accepted image file !"); } //Delete old temp profile pictures AppFileHelper.DeleteFilesInFolderIfExists(_appFolders.TempFileDownloadFolder, "userProfileImage_" + AbpSession.GetUserId()); //Save new picture var fileInfo = new FileInfo(profilePictureFile.FileName); var tempFileName = "userProfileImage_" + AbpSession.GetUserId() + fileInfo.Extension; var tempFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, tempFileName); System.IO.File.WriteAllBytes(tempFilePath, fileBytes); using (var bmpImage = new Bitmap(tempFilePath)) { return(Json(new AjaxResponse(new { fileName = tempFileName, width = bmpImage.Width, height = bmpImage.Height }))); } } catch (UserFriendlyException ex) { return(Json(new AjaxResponse(new ErrorInfo(ex.Message)))); } }
private void Initialize() { int bufferSize = ImageFormatHelper.ComputeBufferSize(configuration.Width, configuration.Height, configuration.ImageFormat); try { background = new byte[bufferSize]; frameBuffer = new byte[bufferSize]; InitializeTimestamp(); allocated = true; } catch { } }