How can I add a png image as a watermark to a larger image using Xamarin.iOS c# and save the output to the device?
I figured out the Xamarin.Android version from another question posted here.
Thanks in Advance!!
Using an image context, you can draw the original, then the watermark at the necessary location and obtain a new image from the context.
ImageContext example:
var originalImage = UIImage.FromBundle("buymore.jpg");
var watermarkImage = UIImage.FromFile("vs.png");
UIGraphics.BeginImageContextWithOptions(originalImage.Size, true, 1.0f);
originalImage.Draw(CGPoint.Empty);
watermarkImage.Draw(new CGRect(new CGPoint(200, 200), watermarkImage.Size));
var processedImage = UIGraphics.GetImageFromCurrentImageContext();
If your original and watermark images are the same size, you can use a CIFilter (CISourceOverCompositing) to "overlay" one image on top of another (assuming your watermark has a white or alpha background. This is my preferred method due to the speed.
CISourceOverCompositing example:
UIImage processedimage;
using (var filter = new CISourceOverCompositing())
{
filter.Image = new CIImage(UIImage.FromBundle("vs.png"));
filter.BackgroundImage = new CIImage(UIImage.FromBundle("buymore.jpg"));
processedimage = UIImage.FromImage(filter.OutputImage);
}
Related
I would like to be able to fill graphics objects using the tiling pattern functionality that pdf offers. For example, I would like to be able to draw something like this:
iText7 has a few objects related to patterns that could be useful, but I am having trouble figuring out how to use them and it is exceedingly difficult to find examples of similar code online.
iText7 provides the following classes that may be useful:
PdfPattern.Tiling
PatternColor
PdfPatternCanvas
It looks like you should be able to create a PdfPattern.Tiling object which references an image in some way and then create a PatternColor from that tiling object. Then you can set your canvas' fill color to the PatternColor you just created. An example of a function that does this is:
private void SetImageTilingFill(PdfCanvas canvas, PdfImageXObject img)
{
PdfPattern.Tiling tiling = new PdfPattern.Tiling((float)Inches2Points(img.GetHeight() / 96), (float)Inches2Points(img.GetWidth() / 96)); // create tiling object with width and height the size of the img
tiling.GetResources().AddImage(img);// add the image as a resource?
canvas.SetFillColor(new PatternColor(tiling)); // set fill color to PatternColor?
}
So far this approach has not been successful, my rectangle ends up solid black. Any suggestions would be much appreciated.
Using an image as a tile requires setting up the tile (it has a canvas to draw on). And then using it as a fill when drawing.
try (PdfWriter writer = new PdfWriter("tiling.pdf");
PdfDocument document = new PdfDocument(writer)) {
// creating image
ImageData imageData = ImageDataFactory.create("wavy.png");
PdfImageXObject imageXo = new PdfImageXObject(imageData);
// setting up the tile
PdfPattern.Tiling imageTile = new PdfPattern.Tiling(100, 100);
new PdfPatternCanvas(imageTile, document)
.addXObjectFittedIntoRectangle(imageXo, new Rectangle(0, 0, 100, 100))
.release();
PdfPage page = document.addNewPage();
PdfCanvas canvas = new PdfCanvas(page);
//using the tile
canvas.setFillColor(new PatternColor(imageTile));
canvas.rectangle(10, 10, 500, 900).fill();
canvas.release();
}
My code can make DropShadow for TextBlock but cannot create it for image if I create image from screen shot. Using normal image (Image source has been set already) problem do not occur.
I believe that problem must be in image format (somehow) I get from screen shot. Any way to convert SoftwareBitmap to other format or what to do?
(To test with TextBlock just replace Image with TextBlock in the first snippet)
Code to copy any element on the screen to image
public static async Task<Image> GetScreenShotFromElement(FrameworkElement TargetFrameworkElement)
{
Image RenderedImage = new Image();
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(TargetFrameworkElement);
RenderedImage.Source = renderTargetBitmap;
return RenderedImage;
}
Code to make drop shadow
public static void CreateDropShadowForImage(Image SOURCE,Grid SHADOWHERE)
{
Visual SOURCE_Visual = ElementCompositionPreview.GetElementVisual(SOURCE);
Compositor SOURCE_compositor = SOURCE_Visual.Compositor;
DropShadow DROP_SHADOW = SOURCE_compositor.CreateDropShadow();
DROP_SHADOW.Mask = SOURCE.GetAlphaMask();
DROP_SHADOW.Offset = new Vector3(10, 10, 0);
SpriteVisual SPRITE_VISUAL = SOURCE_compositor.CreateSpriteVisual();
SPRITE_VISUAL.Size = SOURCE.RenderSize.ToVector2();
SPRITE_VISUAL.Shadow = DROP_SHADOW;
ElementCompositionPreview.SetElementChildVisual(SHADOWHERE, SPRITE_VISUAL);
// Make sure size of shadow host and shadow visual always stay in sync
var bindSizeAnimation = SOURCE_compositor.CreateExpressionAnimation("hostVisual.Size");
bindSizeAnimation.SetReferenceParameter("hostVisual", SOURCE_Visual);
SPRITE_VISUAL.StartAnimation("Size", bindSizeAnimation);
}
I am trying to draw some string to bitmap at certain position and copy a barcode bitmap to the new bitmap.I have not done with graphics before so i don't know where to start.
Can anyone guide me on this?my output of the bitmap is a receipt like.
Here is a solution. Please make a grid or canvas and put the barcode image and use a label with desired text and put the label on desired location relative to barcode grid. So, trick is you can immediately take screenshot of this grid using following code.Then, you are done.
public void ConvertToBitmapSource(UIElement element)
{
var target = new RenderTargetBitmap(
(int)element.RenderSize.Width, (int)element.RenderSize.Height,
96, 96, PixelFormats.Pbgra32);
target.Render(element);
var encoder = new PngBitmapEncoder();
var outputFrame = BitmapFrame.Create(target);
encoder.Frames.Add(outputFrame);
using (var file = File.OpenWrite("TestImage.png"))
{
encoder.Save(file);
}
}
i am using BarcodeInter25 class to make barcode. I am able to make it but its just blur how can it become more sharp ??
also its background white colour is not completely white
My Code:
BarcodeInter25 code25 = new BarcodeInter25();
Rectangle r = new iTextSharp.text.Rectangle(38, 152);
code25.ChecksumText = false;
code25.Code = "some digits";
code25.BarHeight = 2
System.Drawing.Image i = code25.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White);
MemoryStream ms = new MemoryStream();
i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Image img = Image.GetInstance(ms.ToArray());
ms.Dispose();
Looking at your code, it should be obvious why the barcode is blurry. You convert it to a System.Drawing.Image (making it a raster image) and then you convert it to an iTextSharp.text.Image (but by then the image is already blurry).
The correct way to achieve what you want, is to create an iTextSharp.text.Image straight from the barcode (do not pass through System.Drawing.Image). This can be done like this:
BarcodeInter25 code25 = new BarcodeInter25();
Rectangle r = new iTextSharp.text.Rectangle(38, 152);
code25.ChecksumText = false;
code25.Code = "some digits";
code25.BarHeight = 2;
PdfContentByte cb = writer.DirectContent;
Image img = code25.CreateImageWithBarcode(cb, null, null);
Now the Image object won't be a raster image (with pixels that make the lines blurry), but it will be a true vector image (no pixels, but instructions such as moveTo(), lineTo() and stroke()). Vector data has the advantage that it is resolution independent: you can zoom in and zoom out as much as you want, it will always be sharp.
This is explained in Chapter 10 of my book where you'll find the Barcodes example. In that chapter, you'll also discover the setFont() (or in iTextSharp the Font property). I quote from the API documentation:
public void setFont(BaseFont font)
Sets the text font.
Parameters:
font - the text font. Set to null to suppress any text
So if you don't want to see any text, you can add the following line to the above code snippet:
code25.Font = null;
You should avoid re-sizing by any means. The output is most likely pixel-perfect but when you scale it up/down a bilinear filter will smooth it rendering it blurry.
I had the same exact problem by embedding a QRC code in a PDF and solved it by avoiding a resize.
If you really need a different size apply it programmatically in code by using the correct interpolation algorithm.
I have a .png image i wish to overlay on a base image.
My overlay image contains just a red slant line. I need to get the red line overlayed on the base image at the same co-ordinate as it is in overlay image.
The problem is I do not have the co-ordinates location.
I need to find it programmatically with C#. The overlay image will always be transparent or of white background. What code to find the line co-ordinates from overlay image?
You can create new image, render background image first and then render overlay image over it. Since overlay has alpha channel and line is placed where it should be (i mean there is opaque space on top and left side of line) you do not need coordinates. Illustration code:
Image imageBackground = Image.FromFile("bitmap1.png");
Image imageOverlay = Image.FromFile("bitmap2.png");
Image img = new Bitmap(imageBackground.Width, imageBackground.Height);
using (Graphics gr = Graphics.FromImage(img))
{
gr.DrawImage(imageBackground, new Point(0, 0));
gr.DrawImage(imageOverlay, new Point(0, 0));
}
img.Save("output.png", ImageFormat.Png);
If you are using WPF, why not use a path for your overlay instead of an image if it is a simple line? This would allow it to scale to any size, and has methods for manipulating its dimensions.
If you are using Winforms, there are some similar graphics drawing capabilities you might leverage. Getting the dimensions of the image should be easy, assuming you're using a PictureBox, the following properties should suffice:
myPictureBox.Top
myPictureBox.Bottom
myPictureBox.Left
myPictureBox.Right
Similarly, for a WPF Image:
myImage.Margin
I already needed to create a blank space around an image and I used the ImageFactory library to do that.
Here is the code. I guess you are capable to figure out how to adjust to your needs.
public static Image ResizedImage(Image image, int desiredWidth, int desiredHeight)
{
Image res = (Bitmap)image.Clone();
Image resizedImage;
ImageLayer imageLayer = new ImageLayer();
try
{
if (res != null)
{
//white background
res = new Bitmap(desiredWidth, desiredHeight, res.PixelFormat);
//image to handle
using (var imgf = new ImageFactory(true))
{
imgf
.Load(image)
.Resize(new ResizeLayer(new Size(desiredWidth, desiredHeight),
ResizeMode.Max,
AnchorPosition.Center,
false));
resizedImage = (Bitmap)imgf.Image.Clone();
}
//final image
if (resizedImage != null)
{
imageLayer.Image = resizedImage;
imageLayer.Size = new Size(resizedImage.Width, resizedImage.Height);
imageLayer.Opacity = 100;
using (var imgf = new ImageFactory(true))
{
imgf
.Load(res)
.BackgroundColor(Color.White)
.Overlay(imageLayer);
res = (Bitmap)imgf.Image.Clone();
}
}
}
}
catch (Exception ex)
{
ex.Message;
}
return res;
}