protected void processImage() { using (LoadedImage sourceImage = ImageArchiver.LoadImage(this.imgSource.ImageUrl)) { // Generate the image #1 string outputImageFileName = "~/repository/output/Ex_A_105___1.jpg"; new ScaledResizeConstraint(150, 250).SaveProcessedImageToFileSystem(sourceImage, outputImageFileName); this.imgOutput1.ImageUrl = outputImageFileName + "?timestamp=" + DateTime.UtcNow.Ticks.ToString(); // Generate the image #2 outputImageFileName = "~/repository/output/Ex_A_105___2.jpg"; new FixedCropConstraint(150, 250).SaveProcessedImageToFileSystem(sourceImage, outputImageFileName); this.imgOutput2.ImageUrl = outputImageFileName + "?timestamp=" + DateTime.UtcNow.Ticks.ToString(); // Generate the image #3 outputImageFileName = "~/repository/output/Ex_A_105___3.jpg"; new ImageProcessingJob(new ImageProcessingFilter[] { new FixedResizeConstraint(150, 250), DefaultColorFilters.Grayscale }).SaveProcessedImageToFileSystem(sourceImage, outputImageFileName); this.imgOutput3.ImageUrl = outputImageFileName + "?timestamp=" + DateTime.UtcNow.Ticks.ToString(); } this.phOutputContainer.Visible = true; this.phCodeContainer.Visible = true; }
protected void ProcessImage() { // Setup the source file name and the output file name string sourceImageFileName = this.imgSource.ImageUrl; string outputImageFileName = "~/repository/output/Ex_A_224.jpg"; ImageWatermark imageWatermark = null; switch (this.ddlImageSource.SelectedIndex) { case 0: // piczardWatermark1.png // In this demo the image is automatically loaded/disposed by the ImageWatermark class imageWatermark = new ImageWatermark("~/repository/watermark/piczardWatermark1.png"); imageWatermark.ContentAlignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), this.ddlContentAlignment.SelectedValue); imageWatermark.Unit = (GfxUnit)Enum.Parse(typeof(GfxUnit), this.ddlMainUnit.SelectedValue); imageWatermark.ContentDisplacement = new Point(int.Parse(this.ddlContentDisplacementX.SelectedValue, CultureInfo.InvariantCulture), int.Parse(this.ddlContentDisplacementY.SelectedValue, CultureInfo.InvariantCulture)); imageWatermark.Alpha = int.Parse(this.ddlAlpha.SelectedValue, CultureInfo.InvariantCulture); // Process the image imageWatermark.SaveProcessedImageToFileSystem(sourceImageFileName, outputImageFileName); break; case 1: // codeCarvingsWatermark1.gif // In this demo the image is manually loaded/disposed (useful when you need to apply the same // watermark to multiple images) using (LoadedImage image = ImageArchiver.LoadImage("~/repository/watermark/codeCarvingsWatermark1.gif")) { imageWatermark = new ImageWatermark(image.Image); imageWatermark.ContentAlignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), this.ddlContentAlignment.SelectedValue); imageWatermark.Unit = (GfxUnit)Enum.Parse(typeof(GfxUnit), this.ddlMainUnit.SelectedValue); imageWatermark.ContentDisplacement = new Point(int.Parse(this.ddlContentDisplacementX.SelectedValue, CultureInfo.InvariantCulture), int.Parse(this.ddlContentDisplacementY.SelectedValue, CultureInfo.InvariantCulture)); imageWatermark.Alpha = int.Parse(this.ddlAlpha.SelectedValue, CultureInfo.InvariantCulture); // Process the image imageWatermark.SaveProcessedImageToFileSystem(sourceImageFileName, outputImageFileName); } break; } // Update the displayed image (add a timestamp parameter to the query URL to ensure that the image is reloaded by the browser) this.imgOutput.ImageUrl = outputImageFileName + "?timestamp=" + DateTime.UtcNow.Ticks.ToString(); // Display the generated image this.phOutputContainer.Visible = true; }
protected void loadImage(string sourceImagePath) { // Store the source image path (it's used in the ddlCropOrientation_SelectedIndexChanged event handler) this.lastLoadImagePath = sourceImagePath; // Get the source iamge size System.Drawing.Size sourceImageSize; using (LoadedImage image = ImageArchiver.LoadImage(sourceImagePath)) { sourceImageSize = image.Size; } // Auto detect the image orientation if (sourceImageSize.Width > sourceImageSize.Height) { // Is a landscape image this.ddlCropOrientation.SelectedIndex = 0; } else { // Is a portrait image this.ddlCropOrientation.SelectedIndex = 1; } // Load the image CropConstraint cropConstraint = this.getCropConstraint(); this.InlinePictureTrimmer1.LoadImageFromFileSystem(sourceImagePath, cropConstraint); if (!this.ddlCropOrientation.Enabled) { // This is the first time an image is loaded... // Refresh some UI elements // Enable the drop down list control this.ddlCropOrientation.Enabled = true; // Enable the "Preview" button this.btnProcessImage.Enabled = true; } }
protected void SaveImage() { string savedImageFileName = ""; FormatEncoderParams formatEncoderParams = null; object source = null; switch (this.ddlSourceType.SelectedIndex) { case 0: // File system source = this.imgLoaded.ImageUrl; break; case 1: // Byte array source = System.IO.File.ReadAllBytes(Server.MapPath(this.imgLoaded.ImageUrl)); break; case 2: // Stream source = System.IO.File.OpenRead(Server.MapPath(this.imgLoaded.ImageUrl)); // Note: The stream will be automatically closed/disposed by the LoadedImage class break; } using (LoadedImage loadedImage = ImageArchiver.LoadImage(source)) { switch (this.ddlImageFormat.SelectedValue) { case "Auto": formatEncoderParams = ImageArchiver.GetDefaultFormatEncoderParams(); break; case "JPEG": formatEncoderParams = new JpegFormatEncoderParams(int.Parse(this.txtJpegQuality.Text)); break; case "GIF": GifFormatEncoderParams gifFormatEncoderParams = new GifFormatEncoderParams(); formatEncoderParams = gifFormatEncoderParams; gifFormatEncoderParams.QuantizeImage = this.cbGifQuantize.Checked; if (this.cbGifQuantize.Checked) { gifFormatEncoderParams.MaxColors = int.Parse(this.ddlGifMaxColors.SelectedValue); } break; case "PNG": PngFormatEncoderParams pngformatEncoderParams = new PngFormatEncoderParams(); formatEncoderParams = pngformatEncoderParams; pngformatEncoderParams.ConvertToIndexed = this.cbPngConvertToIndex.Checked; if (this.cbPngConvertToIndex.Checked) { pngformatEncoderParams.MaxColors = int.Parse(this.ddlPngMaxColors.SelectedValue); } break; } savedImageFileName = "~/repository/output/Ex_A_103" + formatEncoderParams.FileExtension; // IMPORTANT NOTE: Apply a Noop (No Operation) filter to prevent a known GDI+ problem with transparent images // Example: http://forums.asp.net/t/1235100.aspx switch (this.ddlOutputType.SelectedIndex) { case 0: // File system new NoopFilter().SaveProcessedImageToFileSystem(loadedImage.Image, savedImageFileName, formatEncoderParams); break; case 1: // Byte array byte[] imageBytes = new NoopFilter().SaveProcessedImageToByteArray(loadedImage.Image, formatEncoderParams); System.IO.File.WriteAllBytes(Server.MapPath(savedImageFileName), imageBytes); break; case 2: // Stream using (System.IO.Stream stream = System.IO.File.OpenWrite(Server.MapPath(savedImageFileName))) { new NoopFilter().SaveProcessedImageToStream(loadedImage.Image, stream, formatEncoderParams); } break; } } // Update the displayed image (add a timestamp parameter to the query URL to ensure that the image is reloaded by the browser) this.imgSaved.ImageUrl = savedImageFileName + "?timestamp=" + DateTime.UtcNow.Ticks.ToString(); this.phOutputPreview.Visible = true; // Display extension and size of both files this.litLoadedImageFileDetails.Text = System.IO.Path.GetExtension(this.imgLoaded.ImageUrl).ToUpper() + " file (" + (new System.IO.FileInfo(Server.MapPath(this.imgLoaded.ImageUrl))).Length.ToString() + " bytes)"; this.litSavedImageFileDetails.Text = System.IO.Path.GetExtension(savedImageFileName).ToUpper() + " file (" + (new System.IO.FileInfo(Server.MapPath(savedImageFileName))).Length.ToString() + " bytes)"; }
protected void btnSave_Click(object sender, EventArgs e) { // Save the record if (!this.IsValid) { return; } #region Manage the image files #region Delete the previous image files if (this.RecordId != 0) { // UPDATE... if ((!this.Picture1.HasImage) || (this.Picture1.HasNewImage)) { // Delete the previous image if (!string.IsNullOrEmpty(this.Picture1FileName_upload)) { // Delete the uploaded image string picture1FilePath_upload = System.IO.Path.Combine(Server.MapPath("~/repository/store/ex_A_506/picture1/upload/"), this.Picture1FileName_upload); if (System.IO.File.Exists(picture1FilePath_upload)) { System.IO.File.Delete(picture1FilePath_upload); } this.Picture1FileName_upload = ""; // Delete the main image string picture1FilePath_main = System.IO.Path.Combine(Server.MapPath("~/repository/store/ex_A_506/picture1/main/"), this.Picture1FileName_main); if (System.IO.File.Exists(picture1FilePath_main)) { System.IO.File.Delete(picture1FilePath_main); } this.Picture1FileName_main = ""; // Delete the thumbnail string picture1FilePath_thumbnail = System.IO.Path.Combine(Server.MapPath("~/repository/store/ex_A_506/picture1/thumbnail/"), this.Picture1FileName_thumbnail); if (System.IO.File.Exists(picture1FilePath_thumbnail)) { System.IO.File.Delete(picture1FilePath_thumbnail); } this.Picture1FileName_thumbnail = ""; } } } #endregion #region Save the new image if (this.Picture1.HasNewImage) { // Save the uploaded image string picture1folderPath_upload = Server.MapPath("~/repository/store/ex_A_506/picture1/upload/"); this.Picture1FileName_upload = CodeCarvings.Piczard.Helpers.IOHelper.GetUniqueFileName(picture1folderPath_upload, this.Picture1.SourceImageClientFileName); string picture1FilePath_upload = System.IO.Path.Combine(picture1folderPath_upload, this.Picture1FileName_upload); System.IO.File.Copy(this.Picture1.TemporarySourceImageFilePath, picture1FilePath_upload, true); // Generate the main image string picture1folderPath_main = Server.MapPath("~/repository/store/ex_A_506/picture1/main/"); // Get the original file name (but always use the .jpg extension) this.Picture1FileName_main = CodeCarvings.Piczard.Helpers.IOHelper.GetUniqueFileName(picture1folderPath_main, System.IO.Path.GetFileNameWithoutExtension(this.Picture1.SourceImageClientFileName) + ImageArchiver.GetFileExtensionFromImageFormatId(System.Drawing.Imaging.ImageFormat.Jpeg.Guid)); string picture1FilePath_main = System.IO.Path.Combine(picture1folderPath_main, this.Picture1FileName_main); this.Picture1.SaveProcessedImageToFileSystem(picture1FilePath_main); // Genereate the thumbnail image (Resize -> Fixed size: 48x48 Pixel, Jpeg 80% quality) string picture1folderPath_thumbnail = Server.MapPath("~/repository/store/ex_A_506/picture1/thumbnail/"); // Get the original file name (but always use the .jpg extension) this.Picture1FileName_thumbnail = CodeCarvings.Piczard.Helpers.IOHelper.GetUniqueFileName(picture1folderPath_thumbnail, System.IO.Path.GetFileNameWithoutExtension(this.Picture1.SourceImageClientFileName) + ImageArchiver.GetFileExtensionFromImageFormatId(System.Drawing.Imaging.ImageFormat.Jpeg.Guid)); string picture1FilePath_thumbnail = System.IO.Path.Combine(picture1folderPath_thumbnail, this.Picture1FileName_thumbnail); ImageProcessingJob job = this.Picture1.GetImageProcessingJob(); job.Filters.Add(new FixedResizeConstraint(48, 48)); job.SaveProcessedImageToFileSystem(this.Picture1.TemporarySourceImageFilePath, picture1FilePath_thumbnail, new JpegFormatEncoderParams(80)); } #endregion #endregion #region Save the Record into the DB if (this.RecordId != 0) { // UPDATE... using (OleDbConnection connection = ExamplesHelper.GetNewOpenDbConnection()) { // Update the record using (OleDbCommand command = connection.CreateCommand()) { command.CommandText = "UPDATE [Ex_A_506] SET [Title]=@Title, [Picture1_Configuration]=@Picture1_Configuration, [Picture1_PictureTrimmerValue]=@Picture1_PictureTrimmerValue, [Picture1_FileName_upload]=@Picture1_FileName_upload, [Picture1_FileName_main]=@Picture1_FileName_main, [Picture1_FileName_thumbnail]=@Picture1_FileName_thumbnail WHERE [Id]=@Id"; command.Parameters.AddWithValue("@Title", this.txtTitle.Text); // Store the selected configuration index (landscape / portrait) command.Parameters.AddWithValue("@Picture1_Configuration", this.Picture1.SelectedConfigurationIndex); // Store the picture trimmer vale command.Parameters.AddWithValue("@Picture1_PictureTrimmerValue", JSONSerializer.SerializeToString(this.Picture1.Value)); // Store the file names command.Parameters.AddWithValue("@Picture1_FileName_upload", this.Picture1FileName_upload); command.Parameters.AddWithValue("@Picture1_FileName_main", this.Picture1FileName_main); command.Parameters.AddWithValue("@Picture1_FileName_thumbnail", this.Picture1FileName_thumbnail); command.Parameters.AddWithValue("@Id", this.RecordId); command.ExecuteNonQuery(); } } } else { // INSERT... using (OleDbConnection connection = ExamplesHelper.GetNewOpenDbConnection()) { // Insert the new record using (OleDbCommand command = connection.CreateCommand()) { command.CommandText = "INSERT INTO [Ex_A_506] ([Title], [Picture1_Configuration], [Picture1_PictureTrimmerValue], [Picture1_FileName_upload], [Picture1_FileName_main], [Picture1_FileName_thumbnail]) VALUES (@Title, @Picture1_Configuration, @Picture1_PictureTrimmerValue, @Picture1_FileName_upload, @Picture1_FileName_main, @Picture1_FileName_thumbnail)"; command.Parameters.AddWithValue("@Title", this.txtTitle.Text); // Store the selected configuration index (landscape / portrait) command.Parameters.AddWithValue("@Picture1_Configuration", this.Picture1.SelectedConfigurationIndex); // Store the picture trimmer vale command.Parameters.AddWithValue("@Picture1_PictureTrimmerValue", JSONSerializer.SerializeToString(this.Picture1.Value)); // Store the file names command.Parameters.AddWithValue("@Picture1_FileName_upload", this.Picture1FileName_upload); command.Parameters.AddWithValue("@Picture1_FileName_main", this.Picture1FileName_main); command.Parameters.AddWithValue("@Picture1_FileName_thumbnail", this.Picture1FileName_thumbnail); command.ExecuteNonQuery(); } } } #endregion // Clear the temporary files this.Picture1.ClearTemporaryFiles(); this.ReturnToList(); }
protected void btnSave_Click(object sender, EventArgs e) { if (this.ImageUploader.HasNewImage) { // Generate the main image string webPath = this.ImagePath; string path = Server.MapPath(this.ImagePath); // Get the original file name (but always use the .jpg extension) string filename = IOHelper.GetUniqueFileName(path, Path.GetFileNameWithoutExtension(this.ImageUploader.SourceImageClientFileName) + ImageArchiver.GetFileExtensionFromImageFormatId(ImageFormat.Jpeg.Guid)); path = System.IO.Path.Combine(path, filename); webPath = System.IO.Path.Combine(webPath, filename); this.ImageUploader.SaveProcessedImageToFileSystem(path); ScriptManager.RegisterStartupScript(this, this.GetType(), "SaveSuccess", "Upload_SaveSuccess('" + ResolveUrl(webPath) + "');", true); } this.ImageUploader.ClearTemporaryFiles(); }
protected void processImages() { // Delete the previously generated files string[] oldOutputImages = System.IO.Directory.GetFiles(Server.MapPath(OutputImagesFolder)); foreach (string oldOutputImage in oldOutputImages) { System.IO.File.Delete(oldOutputImage); } // Create a new image processing job ImageProcessingJob job = new ImageProcessingJob(); if (this.cbFilterCrop.Checked) { // Add the crop filter job.Filters.Add(new FixedCropConstraint(380, 320)); } if (this.cbFilterColor.Checked) { job.Filters.Add(DefaultColorFilters.Sepia); } if (this.cbFilterWatermark.Checked) { // Add the watermark TextWatermark textWatermark = new TextWatermark(); textWatermark.ContentAlignment = ContentAlignment.BottomRight; textWatermark.ForeColor = Color.FromArgb(230, Color.Black); textWatermark.Text = "Image processed by Piczard"; textWatermark.Font.Size = 12; job.Filters.Add(textWatermark); } // Get the files to process string[] sourceImages = System.IO.Directory.GetFiles(Server.MapPath(SourceImagesFolder)); for (int i = 0; i < sourceImages.Length; i++) { string sourceFilePath = sourceImages[i]; string sourceFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(sourceFilePath); // Get the output image format FormatEncoderParams outputFormat; if (this.rbFormatCustom.Checked) { // Custom format outputFormat = ImageArchiver.GetFormatEncoderParamsFromFileExtension(this.ddlImageFormat.SelectedValue); } else { // Same format as the source image outputFormat = ImageArchiver.GetFormatEncoderParamsFromFilePath(sourceFilePath); } string outputFileName = sourceFileNameWithoutExtension + outputFormat.FileExtension; string outputFilePath = System.IO.Path.Combine(OutputImagesFolder, outputFileName); // Process the image job.SaveProcessedImageToFileSystem(sourceFilePath, outputFilePath); } }
protected override void Apply(ImageProcessingActionExecuteArgs args) { Bitmap result = null; try { // Create the result image result = new Bitmap(350, 350, CodeCarvings.Piczard.CommonData.DefaultPixelFormat); // Set the right image resolution (DPI) ImageHelper.SetImageResolution(result, args.ImageProcessingJob.OutputResolution); using (Graphics g = Graphics.FromImage(result)) { // Use the max quality ImageHelper.SetGraphicsMaxQuality(g); if ((args.IsLastAction) && (!args.AppliedImageBackColorValue.HasValue)) { // Optimization (not mandatory) // This is the last filter action and the ImageBackColor has not been yet applied... // Apply the ImageBackColor now to save RAM & CPU args.ApplyImageBackColor(g); } using (ImageAttributes imageAttributes = new ImageAttributes()) { // Important imageAttributes.SetWrapMode(WrapMode.TileFlipXY); // Draw the scaled image Rectangle destinationRectangle = new Rectangle(75, 52, 200, 200); using (Image resizedImage = new FixedCropConstraint(GfxUnit.Pixel, destinationRectangle.Size).GetProcessedImage(args.Image)) { g.DrawImage(resizedImage, destinationRectangle, 0, 0, resizedImage.Width, resizedImage.Height, GraphicsUnit.Pixel, imageAttributes); // Draw the reflection destinationRectangle = new Rectangle(75, 252, 200, 98); using (Image flippedImage = ImageTransformation.FlipVertical.GetProcessedImage(resizedImage)) { g.DrawImage(flippedImage, destinationRectangle, 0, 0, flippedImage.Width, flippedImage.Height, GraphicsUnit.Pixel, imageAttributes); } } // Draw the mask destinationRectangle = new Rectangle(0, 0, result.Width, result.Height); using (LoadedImage loadedImage = ImageArchiver.LoadImage("~/repository/filters/MyCustomFilter1Mask.png")) { g.DrawImage(loadedImage.Image, destinationRectangle, 0, 0, loadedImage.Size.Width, loadedImage.Size.Height, GraphicsUnit.Pixel, imageAttributes); } } // Draw the text string text = "Generated by 'MyCustomFilter1' on " + DateTime.Now.ToString(); FontDefinition fontDefinition = new FontDefinition(); fontDefinition.Size = 12; //12px using (Font font = fontDefinition.GetFont()) { // Setup the custom parameters g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; using (StringFormat stringFormat = new StringFormat()) { SizeF textSize = g.MeasureString(text, font, int.MaxValue, stringFormat); Size pixelTextSize = new Size(Convert.ToInt32(Math.Round(textSize.Width)), Convert.ToInt32(Math.Round(textSize.Height))); // Calculate the text position Point location = new Point((result.Width - pixelTextSize.Width) / 2, result.Height - 14 - pixelTextSize.Height); // Draw the text using (Brush brush = new SolidBrush(ColorTranslator.FromHtml("#5b615d"))) { g.DrawString(text, font, brush, location, stringFormat); } } } } // Return the image args.Image = result; } catch { // An error has occurred... // Release the resources if (result != null) { result.Dispose(); result = null; } // Re-throw the exception throw; } }