Display an image in WinRT WebView control - c#

Say I have a WebView in my page, with its content loaded by WebView.NavigateToString(string html). Now the problem is the html string contains a few <img> tags like
<img src="http://www.remotefakesite.com/1.jpg" />
however the image can't be downloaded correctly unless the request has a special cookie. But the request is sent by the control, I don't know how to modify the request(adding a cookie to it). I've tried setting HttpRequest.DefaultWebProxy, but it doesn't work for the requests sent by the built-in control.
An alternative solution is downloading the image by my own HttpWebRequest(with the correct cookie) to local folder and then modify the img tag in the html string to
<img src="files:///xxxxx" />
but obviously files:/// scheme is against the security policy of metro apps. Neither ms-appx nor ms-appdata works, because the downloaded images are not part of my project.
Do you have any solution?

I did some test here, and if you can download the image to example in the project folder.
Example in the "Media" folder, then you can open the image using this code:
<img src="ms-appx-web:///Media/10.jpg" />

If the image size isn't a problem, you could try to download it using a custom HTTP request with the required cookies, base64 encode it, and insert it into the src attribute:
<img src="data:image/png;base64,iVBOR8Q..." />
And pass it with the rest of the html to the WebView using the NavigateToString method.
This might not be the best solution in the world, but it just works, compared to other options.

You can enable the Pictures Library capability of your app and use the picture library location for downloading the images. Here is a guide on accessing pictures library.
Update:
The image is then created from the image objects in the pictures library. An example would be:
async private void LoadImage()
{
try
{
IReadOnlyList<Windows.Storage.StorageFile> resultsLibrary =
await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
MessageBlock.Text += "Show image: " + resultsLibrary[0].Name + "\n";
Windows.Storage.Streams.IRandomAccessStream imageStream =
await resultsLibrary[0].OpenAsync(Windows.Storage.FileAccessMode.Read);
Windows.UI.Xaml.Media.Imaging.BitmapImage imageBitmap =
new Windows.UI.Xaml.Media.Imaging.BitmapImage();
imageBitmap.SetSource(imageStream);
ImagePlayer.Source = imageBitmap;
}
catch (Exception ex)
{
MessageBlock.Text += "Exception encountered: " + ex.Message + "\n";
}
}

You can better use this, write just like HTML:
this.InitializeComponent();
string htmContent = #" <html>
<head></head>
<body>
<img src="http://www.remotefakesite.com/1.jpg" />
</body>
</html>";
preview.NavigateToString(htmContent);
Only you need a webview element (here this called "preview")

Related

Adding Image with url to clipboard

I'm trying to figure out how to get an image added to the clipboard with an associated URI.
Adding a link to text is easy:
string html = #"Version:0.9
StartHTML:<<<<<<<1
EndHTML:<<<<<<<2
StartFragment:<<<<<<<3
EndFragment:<<<<<<<4
SourceURL: <<<<<<<5
<html>
<body>
<!--StartFragment-->
<a href='aria: 73571 73570'>test 73571 73570</a>
<!--EndFragment-->
</body>
</html>";
string link = html;
Clipboard.SetText(link, TextDataFormat.Html);
but its not obvious what to do with a picture such as a bitmap.
Has anyone done this?
--- additional info ---
Just to clarify - the image I need to use is a bitmap generated by the program. I need to associate the image with a URI so that when pasted into something like Word, the user can click on the image to go to the link. Adding the bitmap to the clipboard on its own I can do, but its the URI part with it that I'm not sure of.
---- Another edit -----
I've tried going the embedded encoded image route by creating a string with the following in it:
Version:0.9
StartHTML:000089
EndHTML:9575818
StartFragment:000242
EndFragment:9575780
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HTML clipboard</title>
</head>
<body>
<!--StartFragment--><a href='aria: 73571 73570'><img src='data:image/png;base64,### Encoded Image removed for brevity ##'>
<!--EndFragment-->
</body>
</html>
if saved as an HTML file, this opens in a browser perfectly and the image lets me click on the link with no problem.
When I tried to use the clipboard:
DataObject obj = new DataObject();
obj.SetData(DataFormats.Html, new MemoryStream(encoding.GetBytes(htmlResult)));
Clipboard.SetDataObject(obj, true);
htmlresult is the string containing the html fragment as shown before. When I try to paste into word, I can't get anything out of it.
I'm now running out of ideas..
You can put multiple items on the clipboard simultaneously. Currently, you're only putting the html content on the clipboard, but not an actual image, and thus, applications pasting it will most likely not see it as image. You'll need to put both into the DataObject before putting it on the clipboard.
One thing I can see is an issue is the fact that the html fragment does not contain a url at all. It contains a raw data block as Base64. If you want it to point to a url, then you should give it a real url, rather than the data:image/png;base64, block. The html block you put on the clipboard is supposed to be additional metadata to go alongside an image, not the image itself.
Also, what is that aria: 73571 73570? That's not a url either.
Anyway, the proper way to put things onto the clipboard from stream is the following:
using (MemoryStream htmlStream = new MemoryStream(encoding.GetBytes(htmlResult)))
{
DataObject obj = new DataObject();
// The html content.
obj.SetData(DataFormats.Html, htmlStream);
// As standard bitmap
obj.SetData(DataFormats.Bitmap, image);
// The 'copy=true' argument means any streams that are used
// can be safely disposed after the operation.
Clipboard.SetDataObject(obj, true);
}
The mentioned image is the image. I'm not sure if this works the same way in wpf though; I've been doing this kind of stuff with the System.Drawing classes.
Do note that this kind of clipboard handling has no transparency support. Technically, the clipboard has no image transparency support, but certain programs can read other formats (like png) from the clipboard to get around that. See this answer for more information on that, though do note that that answer is not written for wpf.

img tag doesnt print thumbnailed photo

im doing a project using .net MVC web Application.
i recently used a code to create a new thumbnail to photos (re defining the sizes of a photo) . and now i'm trying to print the photos using the 'img' tag of HTML but without success.
the thumbnail creating code :
Image thumbnail = Image.FromFile(destPath);
thumbnail = (Image)(new Bitmap(thumbnail, new Size(this.m_thumbnailSize, this.m_thumbnailSize)));
thumbnail.Save(destPathThumb);
now for the img printing :
#Html.DisplayFor(modelitem=>item)
<img class="img-rounded" style="border-radius:50%" src=#item alt="">
item is the path to the picture and it is currect (ive checked serveral times).
any ideas what i could be ?
thank you for helping me ! :)
EDIT: the img tag prints normal pictures -> pictures that my program did not create(as i said,my program created thumbnail pictures)
I wonder if it is not releasing the file lock on the image, I have had that problem in the past. You have to be very careful about releasing those Image and Bitmap objects.
Something like this might work, as it will dispose the image before the page starts using it:
using(Image thumbnailoriginal = Image.FromFile(destPath)){
using(Image thumbnail = (Image)(new Bitmap(thumbnailoriginal, new Size(this.m_thumbnailSize, this.m_thumbnailSize)))){
thumbnail.Save(destPathThumb);
}
}
It seems like a lot of brackets on the end but thats ok.
If it still does not work, can you post the html that is sent to the browser, you can do that using "View page source" from the right-click menu in Chrome.
Now we have the html that is going to the browser, we can see that the src attribute is pulling directly from the C drive, rather than from a web url:
<img class="img-rounded" style="border-radius:50%" alt="" src="C:\Users\Operu\Desktop\dest\Thumbnails\2018\6\Sasuke.png">
Normally we would want to see something more like this:
<img class="img-rounded" style="border-radius:50%" alt="" src="\Thumbnails\Sasuke.png">
Could you post the model and controller files next please, so we can see what type of object the #item is when it hits your view. Then we can hopefully get it to pull the relative url address instead of the file location.

Prevent Chrome from downloading files

I need to display files in a HTML page in an object tag.
I use C# MVC4 to send the file. In my code, I set the "Content-Type" and "Content-Disposition" headers.
When I set the Content-Type to something Chrome dosen't know, it will download the file, regardless of the "Content-Disposition" header.
HTML:
<div>
<object data="http://localhost/UncHelper?path=secrectPath\file.dwg"></object></div>
C#:
public override void ExecuteResult(ControllerContext context)
{
context.RequestContext.HttpContext.Response.AddHeader("Content-Type", _contentType);
context.RequestContext.HttpContext.Response.AddHeader("Content-Disposition", "inline; filename=\"" + _fileName + "\"");
context.HttpContext.Response.WriteFile(_uncPath);
context.HttpContext.Response.End();
}
When I try to display a pdf file (_contentType = application/pdf) everything is fine.
But when I try to display a .dwg (_contentType = application/dwg) Chrome will download the file. How can I prevent this?
(I don't want to set a HTML status of 203 based on the browser or anything like that.)
Thanks!
This is not possible, and is also a slight misunderstanding on your part i think. For a browser to be able to display a file, it first has to be downloaded.. This goes for all file types. For instance, if you were displaying an image of image/jpeg, with the disposition set to inline, the browser still downloads the image, and then displays it inline, instead of asking the user where he/she would like to save it. If the browser has no knowledge of how to display the file, this is not an option, and will default to the only other option, which is to ask the user where to save it.

Html Image control not displaying image

Below is my html image control:
<img alt="" src="C:\Users\hkalidindi\Desktop\Feedback.jpg" style="height: 19px; width: 20px"/>
But after debugging it is not showing me any image:
I am new to dotnet..please help me to solve this issue...I know how to display image in image control but i am bit confused about the html image control...
Use image only from the content of your website. So copy the image in your website folder say Images and access your image as <img alt="" src="..\images\Feedback.jpg" style="height: 19px; width: 20px"/>. Or you could use Asp.NET Image control and set image path in Server code using
myImage.ImageUrl=Server.MapPath("Images\Feedback.jpg");
"C:\Users\hkalidindi\Desktop\"
Is only local, try uploading it to a website such as http://imageshack.us, http://tinypic.com, grab the direct link and put that in the source.
<img src="URL">
Here URL = The url of the image.
Possible values (for src):
An absolute URL - points to another web site (like src="http://www.example.com/image.gif")
A relative URL - points to a file within a web site (like src="image.gif")
Refer: HTML src Attribute
You are trying to call the image in your local folder. Add the image to the 'Images' folder in your solution and link to that.
Make sure the image is being referenced from a folder that is in your websites application/dir. Then you can reference it simply by using a tag like so:
<asp:Image id="imgFeedback" runat="server" ImageUrl="~/_common/img/feedback.jpg" />
Or set the image path on the server side:
this.imgFeedback.ImageUrl = Server.MapPath("\_common\img\feedback.jpg\");

How to consume an asp.net image resizer with javascript

I use javascript/jquery to fill with html a web page. In IE works fine but in Firefox or Chrome the image is not shown wherever the image is shown when i click only the link:
http://localhost:12240/ImageResize.aspx?imgsrc=images/test.jpg&width=100
With javascript i create this html code:
<div class="item related-padding">
<div class="item-container item-0">
<div class="item-content" style="background:url(ImageResize.aspx?imgsrc=images/test.jpg&width=127) no-repeat;"></div>
<div class="item-type video"></div>
</div>
<div class="item-caption">Test</div>
</div>
I believe the problem is in C#, ASP.NET headers
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpg";
Random random = new Random();
int randomNumber = random.Next(1000000);
//Response.AddHeader("content-disposition", "attachment;filename=" + $randomNumber.ToString() + ".jpg");
/*resize happens here*/
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.Flush();
Response.End();
bmp.Dispose();
image.Dispose();
any ideas?
All i want is to resize the image and output it as jpg
Add the <img src="ImageResize.aspx?imgsrc=images/test.jpg&width=127" alt=""/> instead of div with background image.
Your question misses the details needed for a to-the-point answer, but here are some hints you can look at:
Relative URIs in CSS are not always treated the same way, check with FireBug or an HTTP sniffer whether the correct relative URI is being retrieved. There used to be a difference here between IE and others, not sure it's still the same.
It's very likely that the error is in your JavaScript, which you don't show. You can check that with the javascript console and/or by printing out the result in an alert box or textbox and rendering that by hand, see what happens (look carefully at correct escaping).
You don't use an entity for the ampersand, though I can hardly imagine a browser would care about that
You don't do a Response.Clear(), which, if you create the response through a normal page request, can create a crippled response stream with headers and data from the page that you don't want there.
Test your code with a regular image on file, see if the CSS still holds (and the JavaScript, of course). Test JavaScript output and CSS separately to make sure to find the right guilty party (CSS, JS, server side C# or else).

Categories