I'm using this solution to apply water-mark to image, here is my code:
for (int i = 0; i < Request.Files.Count; i++)
{
Image imgg = Image.FromFile(Server.MapPath(#"\Images\WaterMark.png"));
HttpPostedFileBase file = Request.Files[i];
using (Image image = Image.FromStream(file.InputStream, true, true)) //Parameter is not valid exception on uploading .webp file
using (Image watermarkImage = imgg)
{
using (Graphics imageGraphics = Graphics.FromImage(image))
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = 4;
int y = image.Height - watermarkImage.Height - 30;
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush,
new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
string extension = System.IO.Path.GetExtension(file.FileName);
filename = "temp" + DateTime.UtcNow.Ticks + extension;
filename = Server.MapPath(#"~\Images\Ads\" + filename);
var i2 = new Bitmap(image);
// image.Save(Server.MapPath(#"~\Images\Ads\" + filename));
System.IO.Directory.CreateDirectory(Server.MapPath(#"~\Images\Ads\"));
i2.Save(filename);
}
}
}
This works fine for all images except .webp. When I upload .webp image i get following exception on Image.FromStream
Parameter is not valid
How can i apply watermark on .webp image?
Related
I insert a watermark for the photos on my site and my photos are in A4 resolution and I don't want reduce the resolution of my photos.
but when I try to watermark a photo, I get an "out of memory" error.
My watermark codes are like this. Please help if you can.
The error appears on the third line of the (using (Graphics imageGraphics = Graphics.FromImage(image))) block of code:
using (Image image = Image.FromFile(HttpContext.Current.Server.MapPath(RawImage)))
using (Image watermarkImage = Image.FromFile(HttpContext.Current.Server.MapPath(qrCode)))
using (Graphics imageGraphics = Graphics.FromImage(image))
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = 0;
int y = 0;
x = ((image.Width - 75) - (watermarkImage.Width));
y = ((image.Height - 75) - (watermarkImage.Height));
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1,watermarkImage.Height)));
Random rnd = new Random();
string datetime = DateTime.Now.ToShortDateString().Replace("/", "") + "_" + DateTime.Now.ToShortTimeString().Replace(":", "").Replace(" ", "").Replace("AM", "").Replace("PM", "").Replace("ب.ظ", "").Replace("ق.ظ", "");
image.Save(HttpContext.Current.Server.MapPath(finalLink.Replace("https://savisgroups.com","~")));
return (finalLink);
}
I want add tiling/repeat watermark to image by using ImageSharp 1.0.0-beta7.
I need figure out how many watermarks and how many points where watermark display. Then use DrawText function to draw one by one.
Is there any extension or library to fill tiling / repeat watermark once with ImageSharp ?
Here's the solution using ImageSharp 2.1, ImageSharp.Drawing 1.0-beta14, and SixLabors.Fonts 1.0-beta16
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.Processing;
using Color = SixLabors.ImageSharp.Color;
using PointF = SixLabors.ImageSharp.PointF;
//enumerate all jpeg files
var files = Directory.EnumerateFiles(Environment.CurrentDirectory).Where(x => x.EndsWith(".jpg") || x.EndsWith(".jpeg"));
//make a watermark of the filename on the files
foreach (var file in files)
{
if (file.Contains(" - Watermark"))
{
continue;
}
Console.WriteLine($"Working on {file}");
var original = Path.GetFileNameWithoutExtension(file);
var directory = Path.GetDirectoryName(file);
var extension = Path.GetExtension(file);
var filename = Path.GetFileNameWithoutExtension(file);
filename += " - Watermark";
//load file with imagesharp
using (var image = Image.Load(file))
{
var fontColl = new FontCollection().AddSystemFonts();
FontFamily fontFamily1 = fontColl.Families.FirstOrDefault(x => x.Name == "Arial");
var font = new Font(fontFamily1, 12, FontStyle.Bold);
TextOptions textoptions = new(font);
var drawingoptions = new DrawingOptions();
drawingoptions.GraphicsOptions.BlendPercentage = 0.5f;
//find out how big the text is
var textSize = TextMeasurer.Measure(original, textoptions);
var pointf = new PointF(0, 0);
int i = 0;
//loop over the height of the image
for (float y = 0; y < image.Height; y += (int)textSize.Height)
{
//loop over the width of the image
for (float x = 0; x <= image.Width; x += (int)textSize.Width)
{
//draw the text on the image
pointf = new PointF(x, y);
//alternate the start of the odd rows to offset the text
if (i % 2 == 0)
pointf.X -= textSize.Width / 2;
image.Mutate(x => x.DrawText(drawingoptions, original, font, Color.White, pointf));
}
i++;
}
//save image
image.Save($"{directory}\\{filename}{extension}");
}
}
Console.ReadLine();
I'm trying to convert pdf to image with ghostscript.net (1.2.1.0) and gs version is 9.22 x86.
my code:
using (_rasterizer = new GhostscriptRasterizer())
{
_rasterizer.Open(inputPdfPath, _lastInstalledVersion, false);
//_rasterizer.CustomSwitches.Add("-sDEVICE=pngalpha");
//_rasterizer.CustomSwitches.Add("-dTextAlphaBits=4");
//_rasterizer.CustomSwitches.Add("-dGraphicsAlphaBits=4");
for (int pageNumber = 1; pageNumber <= _rasterizer.PageCount; pageNumber++)
{
var desiredDPI = 102;
using (System.Drawing.Image img = _rasterizer.GetPage(desiredDPI, desiredDPI, pageNumber))
{
img.Save(pageNumber + ".png", ImageFormat.Png);
}
}
}
it works for some pages, but for some images, it create black margin and black background.
sample files:
pdf => png
I test with gs command, it was ok.
I tried following code. images was good but text was low quality.
public Image getImg(string inputFile, int pageNO, int resolution)
{
GhostscriptPngDevice dev = new GhostscriptPngDevice(GhostscriptPngDeviceType.PngAlpha);
dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.ResolutionXY = new GhostscriptImageDeviceResolution(resolution, resolution);
dev.InputFiles.Add(inputFile);
dev.Pdf.FirstPage = pageNO;
dev.Pdf.LastPage = pageNO;
dev.CustomSwitches.Add("-dDOINTERPOLATE");
dev.OutputPath = pageNO + ".png";
dev.Process();
return Image.FromFile(pageNO + ".png");
}
GhostscriptPngDevice dev = new GhostscriptPngDevice(GhostscriptPngDeviceType.Png16m);
dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.BackgroundColor = Color.White;
dev.ResolutionXY = new GhostscriptImageDeviceResolution(desired_x_dpi, desired_y_dpi);
dev.InputFiles.Add(inputPathAndFile);
dev.Pdf.FirstPage = 1;
dev.Pdf.LastPage = 1;
dev.CustomSwitches.Add("-dDOINTERPOLATE");
dev.OutputPath = outputPathAndFile;
dev.Process();
i want to compress pictures in asp.net but the code i use those not fully compressing the files as soon are still very huge. How can i further reduce the size?
string directory = Server.MapPath("~/listingImages/" + date + filename);
// Create a bitmap of the conten t of the fileUpload control in memory
Bitmap originalBMP = new Bitmap(AsyncFileUpload1.FileContent);
// Calculate the new image dimensions
decimal origWidth = originalBMP.Width;
decimal origHeight = originalBMP.Height;
decimal sngRatio = origHeight / origWidth;
int newHeight = 300; //hight in pixels
decimal newWidth_temp = newHeight / sngRatio;
int newWidth = Convert.ToInt16(newWidth_temp);
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.Bicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
newBMP.Save(Server.MapPath("~/listingImages/" + date + filename));
Try setting the compressipn using this:
public static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
} return null;
}
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)70);
ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
newBMP.Save(Server.MapPath("~/listingImages/" + date + filename), ici, ep);
Check this link for more details: https://msdn.microsoft.com/en-us/library/system.drawing.imaging.encoder.quality%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396.
Maybe you should specify image-format:
newBMP.Save(Server.MapPath("~/listingImages/" + date + filename), System.Drawing.Imaging.ImageFormat.Png);
Hi frnds can anyone help me to solve this problem because i am new for .net world..
The below code is working fine in local server but whenever i try to upload in server it's
getting
"A generic error occurred in GDI+."
if (FileUpload2.PostedFile.ContentType == "image/pjpeg" || FileUpload2.PostedFile.ContentType == "image/jpg" || FileUpload2.PostedFile.ContentType == "image/gif" || FileUpload2.PostedFile.ContentType == "image/jpeg" || FileUpload2.PostedFile.ContentType == "image/png")
{
string filename = FileUpload2.FileName;
// Specify a upload directory
string directory = Server.MapPath(#"datalistimg\");
// Create a bitmap in memory of the content of the fileUpload control
Bitmap originalBMP = new Bitmap(FileUpload2.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int newWidth = 218;
int newHeight = (newWidth * origHeight) / origWidth;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
// Save the new graphic file to the server
newBMP.Save(directory + filename);
dfn2 = #"datalistimg/" + filename;
originalBMP = null;
newBMP = null;
oGraphics = null;
fn2 = System.IO.Path.GetFileName(FileUpload2.PostedFile.FileName);
string SaveLocation = Server.MapPath("event") + "\\" + fn2;
fn2 = "event/" + fn2;
FileUpload2.PostedFile.SaveAs(SaveLocation);