in Documentations, I find How to save the full page - link to article
but for me need save only one element from page to jpg
It's really?
How can I do it with DotNetBrowser?
DotNetBrowser does not provide an API which allows saving the specific DomElement as a JPG.
However, if you need to save resources (such as images, favicons, etc.) from the webpage, take a look at the Browser.Context.NetworkService.ResourceHandler interface. Here is a code snippet:
class SampleResourceHandler : ResourceHandler
{
public bool CanLoadResource(ResourceParams parameters)
{
if (parameters.ResourceType == ResourceType.IMAGE)
{
Console.WriteLine("image URL: " + parameters.URL);
}
return true;
}
}
This article contains more information about how to handle resources loading
Related
I'm using an image processing API which resizes and reformats an image from jpg to png. During this process the image loses the metadata.
Is there a way to write the metadata back to file.
I can get the xmp metadata from the original but now I need to write it back to the new file.
This is my code so far using the metadata-extractor framework for .Net
public static void ReadXmpData(string fileLocation)
{
var xmpDirectory = ImageMetadataReader.ReadMetadata(fileLocation).OfType<XmpDirectory>().FirstOrDefault();
foreach (var property in xmpDirectory.XmpMeta.Properties)
{
Console.WriteLine($"Path:\t{(property.Path != null ? property.Path.Trim() : property.Path)}\n" +
$"Namespace:\t{(property.Namespace != null ? property.Namespace.Trim() : property.Namespace)}\n" +
$"Value:\t{(property.Value != null ? property.Value.Trim() : property.Value)} \n\n\n");
}
}
Any help or guidance would be appreciated.
Edit: I am aware that metadata-extractor does not yet support the writing of xmp data
Use ImageMagick.net which will do image transformations without destroying the exif or xmp metadata. I use this for major film/tv studio images and works great.
I am writing an application which generates PDF files from HTML markup (using a third party library to do so).
I'd like to be able to approval test the output of these PDF files so to do so I've been looking at the ApprovalTests.Net library.
My issue is while ApprovalTests.Net has native support for PDF equality checking, the PDF generation tool will generate subtly different internal markup each time the PDF file is generated. (Font file names are compressed and randomized, file id's change etc).
It seems the best way to achieve a good approval test will be to flatten the PDF document into a series of images and use the binary comparison/load an image diff tool to approval test the documents.
This is all fairly trivial.
My problem arises when dealing with multi-page pdf documents. Each page will produce a new image and thus my test needs to loop over each page and check against the approved file.
I cant seem to find any documentation to specify the approved file name.
Can anyone with experience working with the Approval Tests framework provide any insight?
Alternatively any other frameworks which will allow me to approval test a collection of images?
Thanks.
Create a new derived class of ApprovalBinaryWriter and override the GetApprovalFilename and GetReceivedFilename and inject the index into the constructor.
public class CustomBinaryWriter : ApprovalBinaryWriter
{
private readonly int _index;
public CustomBinaryWriter(byte[] data, string extensionWithoutDot, int index)
: base(data, extensionWithoutDot)
{
_index = index;
}
public override string GetApprovalFilename(string basename)
{
return string.Format("{0}_{1}{2}{3}", basename, _index, WriterUtils.Approved, ExtensionWithDot);
}
public override string GetReceivedFilename(string basename)
{
return string.Format("{0}_{1}{2}{3}", basename, _index, WriterUtils.Received, ExtensionWithDot);
}
}
Then you can call this with
Approvals.Verify(new CustomBinaryWriter(doc, "png", 1));
Using Sitecore 6.5, when images are rendered on a web page, a URL such as the one below is used
~/media/OSS/Images/MyImage
But if you add an image from the library in a content editor a path such as below is used
~/media/1CFDDC34C94E460FAA2B1518DCA22360.PNG
This makes sense as it's trying to use a meaningful path when rendered for the web.
We would like to use the first media image path to add images in the content editor in HTML view rather than the default second method. This is because we are actually taking some html files and automatically adding them in to Sitecore via a script and we can change the image paths to a location in the media library if the first image format is used by using a convention so the images should appear in the newly created items. We have now idea about a media library image ID.
The first format does appear to work as images are rendered in the content editor design editor and when the page is rendered but Sitecore marks these as broken links in the Content Editor. Are any ideas on whether we are safe to use this format?
You may want to avoid hard coding paths to media in the rich text field. The second "dynamic link" is an important feature of Sitecore in that it keeps a connection between the media and item in the Links database. This safeguards you if you ever delete or move the media.
Since it sounds like you are importing content from an external source and you already have a means of detecting the image paths, I would recommend (if possible) that you upload the images programmatically and insert the dynamic links.
Below is a function that you can call for uploading to the Media Library and getting back the media item:
Example usage:
var file = AddFile("/assets/images/my-image.jpg", "/sitecore/media library/images/example", "my-image");
The code:
private MediaItem AddFile(string relativeUrl, string sitecorePath, string mediaItemName)
{
var extension = Path.GetExtension(relativeUrl);
var localFilename = #"c:\temp\" + mediaItemName + extension;
using (var client = new WebClient())
{
client.DownloadFile("http://yourdomain.com" + relativeUrl, localFilename);
}
// Create the options
var options = new MediaCreatorOptions
{
FileBased = false,
IncludeExtensionInItemName = false,
KeepExisting = false,
Versioned = false,
Destination = sitecorePath + "/" + mediaItemName,
Database = Factory.GetDatabase("master")
};
// Now create the file
var creator = new MediaCreator();
var mediaItem = creator.CreateFromFile(localFilename, options);
return mediaItem;
}
As for generating the dynamic link to the media, I actually haven't found a Sitecore method to do this, so I resorted to the following code:
var extension = !String.IsNullOrEmpty(Settings.Media.RequestExtension)
? Settings.Media.RequestExtension
: ((MediaItem)item).Extension;
var dynamicMediaUrl = String.Format(
"{0}{1}.{2}",
MediaManager.MediaLinkPrefix,
item.ID.ToShortID(),
extension);
No it will not cause any rendering issue apart from the broken links notification as you noted. Also when you select an image in the editor and select to edit the media folder will be at the root rather than at the image itself. But as Derek has noted, the use of dynamic links is an important feature to make sure your links do not break if something is moved or deleted.
I would add to his answer that since you are adding the text via a script you can detect images in the text using HtmlAgilityPack (already used in Sitecore) or FizzlerEx (more similar to jQuery syntax), use the code he provided to upload the images to the media library, grab the GUID and replace the src. Something along the lines of:
string content = "<whatever your html to go in the rich text field>";
HtmlDocument doc = new HtmlDocument();
doc.Load(content);
foreach(HtmlNode img in doc.DocumentElement.SelectNodes("//img[starts-with(#src, '/media/')]")
{
HtmlAttribute attr = img["src"];
Item scMediaItem = UploadLocalMedia(attr.Value);
attr.Value = GetDynamicMediaUrl(scMediaItem);
}
I have seen open source and commercial PDF components which support Dot net implementation, I think almost every available component in market,but the strange to identify a document that is protected or not, every one is showing in the form of exception rather than a property.Is there anything tricky behind this?
I would expect
Component.Load(inputFile.pdf);
If(Component.isProtected)
{
Component.Open(inputFile.pdf,password);
}
else
{
Component.Open(inputFile.pdf);
}
instead of the following regular approach
Try{
Component.Open(inputFile.pdf);
}
catch(Exception ex)
{
//bad password
//Some exception
}
All can be detected basically by checking for the respective "dictionaries" as described on pages 115 - 136 of the PDF spec: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
This is possible with Aspose.Pdf for .NET, which is a commercial .NET component. It has a boolean property IsEncrypted for encrypted file detection. Sample code is given below.
// load the source PDF doucment
PdfFileInfo fileInfo = new PdfFileInfo(dataDir + "protected.pdf");
// determine that source PDF file is Encrypted with password
bool encrypted = fileInfo.IsEncrypted;
MessageBox.Show("Encrypted: " + encrypted);
I work for Aspose as a Developer Evangelist.
I have a asp.net mvc project. in a speicific views i call the four image from different different folder inside my proect.
sometime image can not be found. i want to set a image for every folder because all 4 folder contain different diffent size of image so i need to set the image of specific size for each folder.
how i can show the default image when the image not found any way to do that.i means call the none.png when the directory not have image who i called in the views.
are their any way to show the image in the case of image not found.
any way to do that in asp.net 4 MVC 3. using web.config or setting anything else.
Easiest way to do this is with a html helper. Please be mindful of the extra performace hit of checking the file system before even showing an image filename. The hit is a small one though, so you won't notice any issues unless you are getting very high traffic. Then you can implement some sort of caching so the app "knows" if the file exists or not.
You can use a custom html helper for it
public static class ImageHtmlHelpers
{
public static string ImageUrlFor(this HtmlHelper helper, string contentUrl)
{
// Put some caching logic here if you want it to perform better
UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl)))
{
return urlHelper.Content("~/content/images/none.png");
}
else
{
return urlHelper.Content(contentUrl);
}
}
}
Then in your view you can just make the url using:
<img src="<% Html.ImageUrlFor("~/content/images/myfolder/myimage.jpg"); %>" />
EDIT: As Jim pointed out, I haven't really addressed the sizing issue. Personally I use automatic size request management/size which is a whole other story, but if you are concerned about the folders/sizes simply pass that information in to build the path. As below:
public static class ImageHtmlHelpers
{
public static string ImageUrlFor(this HtmlHelper helper, string imageFilename, ImageSizeFolderEnum imageSizeFolder)
{
UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
string contentUrl = String.Format("~/content/userimages/{0}/{1}", imageSizeFolder, imageFilename);
if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl)))
{
return urlHelper.Content(String.Format("~/content/userimages/{0}/none.png", imageSizeFolder));
}
else
{
return urlHelper.Content(contentUrl);
}
}
}
Then in your view you can just make the url using:
<img src="<% Html.ImageUrlFor("myimage.jpg", ImageSizeFolderEnum.Small); %>" />
Have suggested an Enum for better programmatic control if the folder is a fixed set, but for a quick and nasty approach, not reason why you can't just use a string if the folder is db generated etc.
Don't know all that much MVC, but here is my idea nonetheless:
Have a specific controller which fetches an image based on whatever your logic. Like Michael said have something (image) returned on a successful audit - meaning if image is found. If not found return a status code 404 or something like that.
Handle the rest via javascript on the client. So in the img tag write something for the onerror event. May be replace the img source w/ your image not found poster image file. Here somewhat (but not exactly) how to do that via jquery.
$(function(){
$('#myimg').error(function(){
$('#result').html("image not found");
});
});
PS: http://jsfiddle.net/Fy9SL/2/ if u are interested in the full demo of jquery code.
public static MvcHtmlString Image(this HtmlHelper helper, string src, string alt)
{
var builder = new TagBuilder("img");
// Put some caching logic here if you want it to perform better
UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(src)))
{
src = urlHelper.Content("~/content/images/none.png");
}
else
{
src = urlHelper.Content(src);
}
builder.MergeAttribute("src", src);
builder.MergeAttribute("alt", alt);
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
You can make a controller action return a FileResult, and accept a parameter of type string which describes the image path.
The controller action tries to load the image from disk and return it as a FileResult, or if the file is missing from the disk, return a place holder 'image not found' image instead.
Then to display the image (or its placeholder) you would set the src attribute of your img element to the controller action rather than the image directly.