Save WF 4 workflow as Image - image

The problem is that I am opening workflow designer dynamically from one shell application and I don't have reference to Canvas. I am able to save the WF4 as image but the image is not getting saved properly and contains left & top margins. I followed many articles to get it working but no success. I referred to following article as well.
Saving a canvas to png C# wpf
I am using the below function. I don't have any reference to canvas.
private BitmapFrame CreateWorkflowImage()
{
const double DPI = 96.0;
Visual areaToSave = ((DesignerView)VisualTreeHelper.GetChild(this.wd.View,
0)).RootDesigner;
Rect bounds = VisualTreeHelper.GetDescendantBounds(areaToSave);
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)bounds.Width,
(int)bounds.Height, DPI, DPI, PixelFormats.Default);
bitmap.Render(areaToSave);
return BitmapFrame.Create(bitmap);
}
Please help on this.

I am able to resolve the issue by referring to again the following link
Saving a canvas to png C# wpf
I got the reference to canvas by using following code
Visual canvas= ((DesignerView)VisualTreeHelper.GetChild(this.WorkflowDesigner1.View, 0)).RootDesigner;
This has resolved the border/margin issue.

Please have a look here: http://blogs.msdn.com/b/flow/archive/2011/08/16/how-to-save-wf4-workflow-definition-to-image-using-code.aspx
let’s look at how to generate an image of the workflow definition using the standard mechanism of WPF. After all, workflow designer canvas is a WPF control.
BitmapFrame CreateWorkflowDefinitionImage()
{
const double DPI = 96.0;
// this is the designer area we want to save
Visual areaToSave = ((DesignerView)VisualTreeHelper.GetChild(
this.workflowDesigner.View, 0)).RootDesigner;
// get the size of the targeting area
Rect size = VisualTreeHelper.GetDescendantBounds(areaToSave);
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height,
DPI, DPI, PixelFormats.Pbgra32);
bitmap.Render(areaToSave);
return BitmapFrame.Create(bitmap);
}
The above C# method is very straightforward. Just get the workflow diagram part of the workflow designer and create an in-memory image of it using some WPF API. The next thing is simple: create a file and save the image.
void SaveImageToFile(string fileName, BitmapFrame image)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(fs);
fs.Close();
}
}
At last, let’s try to invoke the above 2 methods in the OnInitialized() method to hook it up and then close the application.
protected override void OnInitialized(EventArgs e)
{
// ...
this.SaveImageToFile("test.jpg", this.CreateWorkflowDefinitionImage());
Application.Current.Shutdown();
}

Related

.svg Image in MAUI Blazor

i am trying to set an image in to a razor page in MAUI Blazor.
In MAUI (only), there was the aproach, that you have a .svg image in the folder Resources/Images. MAUI then converts the .svg image in a .png image which you can use in the XAML file. like so:
Now i have the same picture in a MAUI Blazor app and i hoped that i can put my picture in the same way expect that i have to use the HTML style like so:
<img src="one_list2.png">
But this doesn't work at all. I tryed with or witout path, path with slashes, backslashes etc. nothing works.
Trying to put a .png image into the wwwroot folder works. But this isn't the goal. I found it very nice to put a svg image which is then converted into a png depending of its size. This way all pictures would be converted exactly in the perfect size you will need lossless.
Thanks
First, Add the image to Resources\Raw and set it to MauiAsset compilation type
Second, Check the project file to avoid setting the image in the other folder.
In razor component HTML:
<img src="#imageSource">
In the code part:
private string? imageSource;
protected override async Task OnInitializedAsync()
{
try
{
using var stream =
await FileSystem.OpenAppPackageFileAsync("testimage.png");
using var reader = new StreamReader(stream);
byte[] result;
using (var streamReader = new MemoryStream())
{
stream.CopyTo(streamReader);
result = streamReader.ToArray();
}
imageSource = Convert.ToBase64String(result);
imageSource = string.Format("data:image/png;base64,{0}", imageSource);
}
catch (Exception ex)
{
//error
}
}
More information you can refer to ASP.NET Core Blazor Hybrid static files.

How to get Resized/Thumbnail Image : UWP

Currently I was working on a UWP application. I captured the ink strokes into an image. Now the same image need to display as a preview. So the original image need to re-size to shorter size or thumbnail need to be generated.
I tried with using the larger image directly as a source to shorter sized image canvas --> not working (visible image quality degrade)
I also used Transcode of image programatically --> same result as above
I test with the same image. Re-sized the same image using paint, and there interestingly the quality of the re-sized image remains good.
Please help me to solve the issue I faced.
I not sure, need to see some code, but could be how you are saving the image? Here an example:
try
{
Windows.Storage.Pickers.FileSavePicker save = new Windows.Storage.Pickers.FileSavePicker();
save.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
save.DefaultFileExtension = “.png”;
save.FileTypeChoices.Add(“PNG”, new string[] { “.png” });
StorageFile filesave = await save.PickSaveFileAsync();
using (IOutputStream fileStream = await filesave.OpenAsync(FileAccessMode.ReadWrite))
{
if (fileStream != null)
{
await m_InkManager.SaveAsync(fileStream);
}
}
}
catch (Exception ex)
{
var dialog = new MessageDialog(ex.Message);
dialog.ShowAsync();
}
I will post a great tutorial of Can Bilgin that explain perfectly all about inking.
Drawing / Inking API in WinRT (C#) – I
Drawing / Inking API in WinRT (C#) – II
Drawing / Inking API in WinRT (C#) – III

Unity 4.6 (new UI): Button click with complex image

I have a Button (Canvas>Panel>Button) with a complex image (is not square), the issue here is that I want it to execute the on click event when i click on the IMAGE (excluding parts of the image with no opacity) but since the new UI doesn't work with colliders I can't achieve the same click behaviour that could be achieved with a polygon collider, and its feels completely wrong to click outside the button (image) where the alpha is cero (0) and still execute the click events..
I hope my problem is clear enough and someone can help me, thanks in advance.
I found a solution, Unity should have an option to achieve this but at least this works perfectly: http://forum.unity3d.com/threads/none-rectangle-shaped-button.263684/#post-1744521
I found another (probably better) solution for this problem. I used a Collider2D (PolygonCollider2D) to define the clickable shape and then used this RaycastFilter:
using UnityEngine;
using UnityEngine.UI;
[RequireComponent (typeof (RectTransform), typeof (Collider2D))]
public class Collider2DRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
Collider2D myCollider;
RectTransform rectTransform;
void Awake ()
{
myCollider = GetComponent<Collider2D>();
rectTransform = GetComponent<RectTransform>();
}
#region ICanvasRaycastFilter implementation
public bool IsRaycastLocationValid (Vector2 screenPos, Camera eventCamera)
{
var worldPoint = Vector3.zero;
var isInside = RectTransformUtility.ScreenPointToWorldPointInRectangle(
rectTransform,
screenPos,
eventCamera,
out worldPoint
);
if (isInside)
isInside = myCollider.OverlapPoint(worldPoint);
return isInside;
}
#endregion
}
Using a collider for this is a bit hacky but the result is much simpler, probably faster and makes it much easier to adjust the clickable shape.
This could be improved by creating a custom alternative to replace the Collider2D but that's a bit too much work for what I need.

iTextSharp: Why when adding a image to a pdf page the text font is different?

I use Helvetica font and 14 px size for text. The problem is that if a page does not have any image on it the text is very clear, but in a page with at least 1 image the text is getting a little bold. You can see what I mean in images below:
* Without image on page
* With image on page
The correct font is the one that appear in picture #1. How to make all pages have the same font even if the page contains an image or not?
Thanks.
Sample code:
Document document = new Document(PageSize.LETTER);
document.SetMargins(docMargin, docMargin, docMargin, 25);
writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
document.Open();
Font defaultFont = FontFactory.GetFont("Helvetica", 7.8, Font.NORMAL, new Color(75, 75, 75));
document.Add(new Paragraph("Lorem ipsum lorem ipsum lorem ipsum", defaultFont));
document.Add(Chunk.NEWLINE);
Image img = Image.GetInstance("my png image path");
document.Add(img);
document.Close();
I was finally able to reproduce your problem. The first PNG that I tested with which didn't reproduce your problem I created from Photoshop and used the Save For Web command. The second PNG that I tested and was able to reproduce your problem I created from MSPAINT.EXE. I tried various combinations within Save For Web and none of them have the same problem as Paint.
According to this thread from the official iText mailing list it appears to be something about the color profile of the image.
What are you seeing is the impact of newly placed transparency into a
PDF that had not previously contained it, when consideration isn't
given for the blending colorspace of the final output document.
You have an RGB document that upon adding transparency is forced into
CMYK due to lack of explicit blending space. If you were to specify
RGB as your explicit blending space at the same time you added your
transparency, all would be well.
One thing they recommend is setting the following property on your PdfWriter before adding anything:
writer.RgbTransparencyBlending = true;
When I do it I still see a very minor shift but no where near as pronounced as without it.
This isn't an answer, I just need to be able to post code.
I'm unable to reproduce your results but if I were to guess it has something to do with your PDF renderer. You can confirm this by zooming in on the text, does it look the same when zoomed in? If so, that's your renderer trying to apply visual hints to a print document. If not, can you post a simplified version of your code that does this? Does this do this for all images or just one specific one? How are you creating your text, with Paragraphs, Tables, HTML parsing or something else? What version of iTextSharp are you using?
Below is a full working WinForms C# 2010 targeting iTextSharp 5.1.2.0 that creates a two page PDF. The first page has just text and the second page has text followed by an image loaded from the desktop. On my machine, using Adobe Acrobat Pro 9.1.3 I don't see any difference in fonts when I view it on screen.
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
string pdfFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
string imgFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.png");
using (FileStream fs = new FileStream(pdfFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.LETTER)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font f = new iTextSharp.text.Font(bf, 14);
doc.NewPage();
doc.Add(new Paragraph("This is a test", f));
doc.NewPage();
doc.Add(new Paragraph("This is a test", f));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgFile);
img.ScaleAbsolute(100, 100);
doc.Add(img);
doc.Close();
}
}
}
this.Close();
}
}
}

How do you convert a HttpPostedFileBase to an Image?

I am using ASP.NET MVC and I've an action that uploads the file. The file is being uploaded properly. But I want width and height of the image. I think I need to convert the HttpPostedFileBase to Image first and then proceed. How do I do that?
And please let me know if there is another better way to get the width and height of the image.
I use Image.FromStream to as follows:
Image.FromStream(httpPostedFileBase.InputStream, true, true)
Note that the returned Image is IDisposable.
You'll need a reference to System.Drawing.dll for this to work, and Image is in the System.Drawing namespace.
Resizing the Image
I'm not sure what you're trying to do, but if you happen to be making thumbnails or something similar, you may be interested in doing something like...
try {
var bitmap = new Bitmap(newWidth,newHeight);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(oldImage,
new Rectangle(0,0,newWidth,newHeight),
clipRectangle, GraphicsUnit.Pixel);
}//done with drawing on "g"
return bitmap;//transfer IDisposable ownership
} catch { //error before IDisposable ownership transfer
if (bitmap != null) bitmap.Dispose();
throw;
}
where clipRectangle is the rectangle of the original image you wish to scale into the new bitmap (you'll need to manually deal with aspect ratio). The catch-block is typical IDisposable usage inside a constructor; you maintain ownership of the new IDisposable object until it is returned (you may want to doc that with code-comments).
Saving as Jpeg
Unfortunately, the default "save as jpeg" encoder doesn't expose any quality controls, and chooses a terribly low default quality.
You can manually select the encoder as well, however, and then you can pass arbitrary parameters:
ImageCodecInfo jpgInfo = ImageCodecInfo.GetImageEncoders()
.Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();
using (EncoderParameters encParams = new EncoderParameters(1))
{
encParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);
//quality should be in the range [0..100]
image.Save(outputStream, jpgInfo, encParams);
}
If you are sure, that the source is image and doesn't need editing, you can do it easily as described here
[HttpPost]
public void Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var filename = Path.GetFileName(file.FileName);
System.Drawing.Image sourceimage =
System.Drawing.Image.FromStream(file.InputStream);
}
}
To secure the file is image, add javascript validation to View by adding accept attribute with MIME type to input tag
<input type="file" accept="image/*">
and jQuery validation script
$.validator.addMethod('accept', function () { return true; });
The whole solution can be found here

Resources