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();
Related
I have some code that uses System.Windows.Forms.DataVisualization.Charting; to generate a chart and create a bitmap image
private Bitmap GetTargetGradingImage(int sessionsTrained, int target, int height, int width)
{
const string TargetSeries = "TargetSeries";
var chart = new Chart
{
Height = height,
Width = width
};
chart.ChartAreas.Add(new ChartArea()
{
Name = "ChartArea1"
});
chart.Series.Clear();
chart.Series.Add(new Series()
{
Name = TargetSeries,
IsVisibleInLegend = true,
ChartType = SeriesChartType.Column,
Color = Color.Green
});
chart.Series[TargetSeries].ChartArea = chart.ChartAreas[0].Name;
string[] XPointMember = new string[2];
int[] YPointMember = new int[2];
XPointMember[0] = "Sessions";
YPointMember[0] = sessionsTrained;
XPointMember[1] = "Target";
YPointMember[1] = target;
chart.Series[TargetSeries].Points.DataBindXY(XPointMember, YPointMember);
chart.Invalidate();
var bitmap = new Bitmap(chart.Size.Width, chart.Size.Height, PixelFormat.Format32bppArgb);
chart.DrawToBitmap(bitmap, chart.Bounds);
//chart.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height));
return bitmap;
}
This works fine on my dev system but not when published to an Azure website. The images are blank.
The images are being used for inclusion in html emails.
Any ideas?
Cracked it.
Didn't need the chart.DrawToBitmap bit at all
This works
using (var chartImage = new MemoryStream())
{
chart.SaveImage(chartImage, ChartImageFormat.Png);
targetBuf = Convert.ToBase64String(chartImage.ToArray());
}
This gives me a Base64 encoded string that I can use in an img tag
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?
I am uploading multiple photos using MultipleFileUpload, if I will upload big size images, then in slider image is not fixed size not showing proper looks. Is there any code for while uploading time restricts the size of images of the gallery.
Below is my c# code:
protected void lnkbtn_Submit_Click(object sender, EventArgs e)
{
try
{
if (MultipleFileUpload.HasFiles)
{
int MaxGalleryId, ReturnValue;
ReturnValue = obj.fnCreateNewPhotoGallery(txtGalleryName.Text, txtGalleryDescrption.Text, DateTime.Now, out MaxGalleryId);
if (ReturnValue != 0)
{
string GalleryPath = System.Configuration.ConfigurationManager.AppSettings["GalleryPath"] + MaxGalleryId;
Directory.CreateDirectory(Server.MapPath(GalleryPath));
string ThumbnailPath = System.Configuration.ConfigurationManager.AppSettings["ThumbnailPath"] + MaxGalleryId;
Directory.CreateDirectory(Server.MapPath(ThumbnailPath));
StringBuilder UploadedFileNames = new StringBuilder();
foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
{
//Upload file
string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
string SaveAsImage = System.IO.Path.Combine(Server.MapPath(GalleryPath + "/"), FileName);
uploadedFile.SaveAs(SaveAsImage);
//Create thumbnail for uploaded file and save thumbnail on disk
Bitmap Thumbnail = CreateThumbnail(SaveAsImage, 200, 200);
string SaveAsThumbnail = System.IO.Path.Combine(Server.MapPath(ThumbnailPath + "/"), FileName);
Thumbnail.Save(SaveAsThumbnail);
}
HTMLHelper.jsAlertAndRedirect(this, "Gallery created successfully. ", "Album.aspx?GalleryId=" + MaxGalleryId);
}
}
}
catch
{
HTMLHelper.jsAlertAndRedirect(this, "Gallery is not created. Some exception occured ", "CreateAlbum.aspx");
}
}
Below is my Create Thumbnail method code :
public Bitmap CreateThumbnail(string ImagePath, int ThumbnailWidth, int ThumbnailHeight)
{
System.Drawing.Bitmap Thumbnail = null;
try
{
Bitmap ImageBMP = new Bitmap(ImagePath);
ImageFormat loFormat = ImageBMP.RawFormat;
decimal lengthRatio;
int ThumbnailNewWidth = 0;
int ThumbnailNewHeight = 0;
decimal ThumbnailRatioWidth;
decimal ThumbnailRatioHeight;
// If the uploaded image is smaller than a thumbnail size the just return it
if (ImageBMP.Width <= ThumbnailWidth && ImageBMP.Height <= ThumbnailHeight)
return ImageBMP;
// Compute best ratio to scale entire image based on larger dimension.
if (ImageBMP.Width > ImageBMP.Height)
{
ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
ThumbnailNewWidth = ThumbnailWidth;
decimal lengthTemp = ImageBMP.Height * lengthRatio;
ThumbnailNewHeight = (int)lengthTemp;
}
else
{
ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
ThumbnailNewHeight = ThumbnailHeight;
decimal lengthTemp = ImageBMP.Width * lengthRatio;
ThumbnailNewWidth = (int)lengthTemp;
}
Thumbnail = new Bitmap(ThumbnailNewWidth, ThumbnailNewHeight);
Graphics g = Graphics.FromImage(Thumbnail);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
g.DrawImage(ImageBMP, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
ImageBMP.Dispose();
}
catch
{
return null;
}
return Thumbnail;
}
The above code there is a command line //Upload file from there uploading images. I used this example for the gallery:
http://www.bugdebugzone.com/2013/10/create-dynamic-image-gallery-slideshow.html
You can the ContentLength property of uploadedFile as such:
if (uploadedFile.ContentLength > 1000000)
{
continue;
}
ContentLength is the size in bytes of the uploaded file.
https://msdn.microsoft.com/en-us/library/system.web.httppostedfile.contentlength(v=vs.110).aspx
I hope you all are Fine, Today I'm experiencing a quite confusing problem.
I'm trying to make a simple application which can convert the PSD to Transparent PNG. But I'm not happy with the results I'm getting.
I'm using Magick.NET-Q16-x86.DLL (MagickImage) with C#
Below is my code snippet, Please review:
ImageMagick.MagickImage image = new MagickImage(filePath+"[0]");
image.Density = new Density("300");
image.Format = MagickFormat.Png32;
image.Write(outputFolder + #"\" + Path.GetFileNameWithoutExtension(filePath) + ".png");
And Here is the Image explaining the Problem:
(Left Side is Expected Result and Right Side Image is the one I'm getting )
So I don't understand whats Happening here. I'd really be thankful if i can get any answer. Thanks a lot for reviewing!
Best,
Maher
The issue with this image is that it does not contain a 'merged image'. This is the image that combines all the layers from your PSD file. And the reader now creates this merged image itself.
The problem with this is that ImageMagick/Magick.NET does not support all features of Photoshop and that is why it creates this image. It might be possible that the image can be read in the future but it will take a lot of time to implement all the PSD features.
Project Console Export Psd to Jpg
public class Tamanho
{
public string NameFolder { get; set; }
public int Width { get; set; }
public int Heigth { get; set; }
public string ImagePath { get; set; }
}
class Program
{
static void Main(string[] args)
{
var PathDefault = #"C:\FOTOSZSA";
DirectoryInfo di1 = new DirectoryInfo(PathDefault);
string strPath = #"c:\ImagensImport\LogErro.txt";
File.Create(strPath).Dispose();
if (!di1.Exists)
{
Directory.CreateDirectory(PathDefault);
}
Tamanho settings = new Tamanho { NameFolder = "1000x1000", Width = 1000, Heigth = 1000, ImagePath = #"C:\ImagensImport\imagem1000x1000\" };
if (Directory.Exists(PathDefault))
{
string[] arquivos = Directory.GetFiles(PathDefault);
var nameFile = "";
var fileResize = "";
foreach (string arquivo in arquivos)
{
try
{
nameFile = Path.GetFileName(arquivo);
if (nameFile.LastIndexOf(".psd") != -1)
{
using (MagickImage image = new MagickImage(PathDefault + #"\" + nameFile))
{
ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
Encoder myEncoder = Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder,50L);
fileResize = settings.NameFolder;
Size newSize = new Size(settings.Width, settings.Heigth);
var bmp1 = ResizeImage(image.ToBitmap(), newSize);
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
bmp1.Save(settings.ImagePath + nameFile + ".Jpg", jgpEncoder,
myEncoderParameters);
image.Dispose();
myEncoderParameter.Dispose();
myEncoderParameters.Dispose();
}
}
}
catch (Exception ex)
{
using (StreamWriter sw = File.AppendText(strPath))
{
sw.WriteLine("=============Error File ===========");
sw.WriteLine("===========NameFile============= " + nameFile);
}
}
}
}
}
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
private static Bitmap ResizeImage(Bitmap mg, Size novoTamanho)
{
using (Bitmap i_Bmp = mg)
{
double ratio = 0d;
double myThumbWidth = 0d;
double myThumbHeight = 0d;
int x = 0;
int y = 0;
Bitmap bp;
if ((mg.Width / Convert.ToDouble(novoTamanho.Width)) > (mg.Height /
Convert.ToDouble(novoTamanho.Height)))
ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(novoTamanho.Width);
else
ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(novoTamanho.Height);
myThumbHeight = Math.Ceiling(mg.Height / ratio);
myThumbWidth = Math.Ceiling(mg.Width / ratio);
//Size thumbSize = new Size((int)myThumbWidth, (int)myThumbHeight);
Size thumbSize = new Size((int)novoTamanho.Width, (int)novoTamanho.Height);
bp = new Bitmap(novoTamanho.Width, novoTamanho.Height);
x = (novoTamanho.Width - thumbSize.Width) / 2;
y = (novoTamanho.Height - thumbSize.Height);
Graphics g = Graphics.FromImage(bp);
g.FillRectangle(Brushes.White, 0, 0, bp.Width, bp.Height);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);
return bp;
}
}
}
Okay, I'm trying to do some work analyzing heuristics of an image in a WPF app. When the user chooses the image file location, I want to open the image in the codebehind, check the colors of the image, and output them in an application. However to properly check the pixels of the image I need to acquire the dimensions to load it to a WriteableBitmap that can get me the pixel colors.
When I open a stream to the file a second time the app just hangs. Here's the code:
private static async Task<Dictionary<Color, int>> GetColorCountsAsync(string path)
{
var colorCounts = new Dictionary<Color, int>();
var absolutePath = string.Format(#"{0}\{1}",Directory.GetCurrentDirectory(),path);
var dimension = await GetBitmapDimensions(absolutePath); //Method below - opens via StorageFile
var file = await StorageFile.GetFileFromPathAsync(absolutePath); //Hangs forever
using (var stream = await file.OpenStreamForReadAsync().ConfigureAwait(false))
{
var pixelWidth = dimension.Width;
var pixelHeight = dimension.Height;
var bitmap = new WriteableBitmap(pixelWidth, pixelHeight);
bitmap.SetSource(stream.AsRandomAccessStream());
using (var buffer = bitmap.PixelBuffer.AsStream())
{
var pixels = new byte[4 * pixelWidth * pixelHeight];
buffer.Read(pixels, 0, pixels.Length);
for (var y = 0; y < pixelHeight; y++)
{
for (var x = 0; x < pixelWidth; x++)
{
var index = ((y * pixelWidth) + x) * 4;
var alpha = pixels[index + 4];
var red = pixels[index + 2];
var green = pixels[index + 1];
var blue = pixels[index + 0];
var color = Color.FromArgb(alpha, red, green, blue);
if (!colorCounts.ContainsKey(color))
{
colorCounts.Add(color, 0);
}
colorCounts[color] = colorCounts[color] + 1;
}
}
}
}
return colorCounts;
}
private static async Task<Dimension> GetBitmapDimensions(string absolutePath)
{
var file = await StorageFile.GetFileFromPathAsync(absolutePath);
var bitmapImage = new BitmapImage();
using (var fileStream = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream);
}
return new Dimension { Height = bitmapImage.PixelHeight, Width = bitmapImage.PixelWidth };
}
I can't close the bitmap image nor dispose it - what's causing the app to freeze?
You don't need the bitmap in the correct dimensions, as SetStream() is an extension method. It just needs an object first, call it like this:
var bitmap = new WriteableBitmap(1,1).SetSource(stream.AsRandomAccessStream());