Following on from the example Access Device Camera with Blazor I would like to view the image on the same page. So far I have found several older examples using JS but I think I should stick to native Blazor.
I think this is the start, but have failed to reference the file that was selected.
<p>
<h1>My Camera App</h1>
</p>
<input #onchange="updateCanvas" id="capturedPic" type="file" accept="image/*" capture>
<br />
<canvas id="picCanvas"> </canvas>
<br />
<br />
#code
{
public void updateCanvas()
{
//Code to place captured image in the canvas;
}
}
Following the .NET5 introduction of InputFile, I have the following solution.
The max size of an image is 500K so the code converts the camera photo to a 100x100 thumbnail.
Many thanks to Daniel https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-5-release-candidate-1/ and Naveen https://www.learmoreseekmore.com/2020/10/blazor-webassembly-fileupload.html
<div>
<InputFile OnChange="#OnFileSelection"></InputFile>
<div class="row">
<img src="#imgUrl">
</div>
</div>
#code{
string imgUrl = string.Empty;
private async Task OnFileSelection(InputFileChangeEventArgs e)
{
IBrowserFile imgFile = e.File;
string imageType = imgFile.ContentType;
var resizedImageFile = await imgFile.RequestImageFileAsync(imageType, 100, 100);
var buffers = new byte[resizedImageFile.Size];
await resizedImageFile.OpenReadStream().ReadAsync(buffers);
imgUrl = $"data:{imageType};base64,{Convert.ToBase64String(buffers)}";
}
}
Related
I've sure I'm missing something simple here, I found a suggestion on here to use jsfiddle for code to preview an image before upload: http://jsfiddle.net/LvsYc/5234/
But I can't get it to work. I'm assuming I just put the javascript in the header wrapped in tags?
Here's my code (thank you - I'm sorry if this is very similar to other questions)
<script language="javascript">
window.onload=function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#artworkshow').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#artwork").change(function(){
readURL(this);
});
</script>
<img id="artworkshow" src="#" alt="Image Preview" />
<p>
<label for="artwork">Artwork</label>
<input id="artwork" name="artwork" type="file" class="inputAuto" />
Size: 700px by 260px</p>
<p>
I want to change the set of 5 image on page refresh called in html.
the images should called this under the body tag:
<img src="images/side-logos/1.jpg" alt="">
<img src="images/side-logos/2.jpg" alt="">
<img src="images/side-logos/4.jpg" alt="">
<img src="images/side-logos/5.jpg" alt="">
I want to called the set of images under the body tag not in javascript.
I have searched a lot on website but everyone calling the image in javascript not under the body tag.
So Please help me if anyone has the solutions for it.
just replace onclick event with window refresh event
HTML
<div id="box">
<img id="image" />
</div>
<br />
<input type="button" value="Randomize!" onClick="randImg()" />
JS
var images = [
"http://static.ddmcdn.com/gif/lightning-gallery-18.jpg",
"http://static.ddmcdn.com/gif/lightning-gallery-19.jpg",
"http://static.ddmcdn.com/gif/lightning-gallery-20.jpg",
"http://static.ddmcdn.com/gif/lightning-gallery-17.jpg"];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
demo
EDIT
new_demo
Unfortunateley, you can only do this with javascript.
To do that, here is some code that is placed in the tags
<script type="text/javascript">
function Randomize() {
var images = new Array("one.jpg","two.jpg","three.jpg","four.jpg");
var imageNum = Math.floor(Math.random() * images.length);
document.getElementById("divid").style.backgroundImage = "url('" + images[imageNum] + "')";
}
window.onload = Randomize;
</script>
The name of the images shoukd be in the images array and the "divid" is where you want the images to appear.
im getting this error "image corrupt or truncated" on FF console when I try to display an image stored in my database. I´m using Grails and Hibernate.
I just want to display a user´s profile picture in my gsp page.
My domain class User has an attribute photo defined as byte[]
public class User {
private String userId;
private byte[] photo;
.
.
.
The user.hbm.xml mapping is :
< property name="photo" type="binary" column="PHOTO" not-null="false" />
This collumn is a BLOB on DB.
My gsp:
< div id="user-view-thumbnail-container">
<fieldset>
<legend>Photo Upload</legend>
<g:form action="uploadPhoto" method="post" enctype="multipart/form-data">
<label for="photo">Photo</label>
<input type="file" name="photo" id="photo" />
<input type="submit" class="buttons" value="Upload" />
</g:form>
</fieldset>
<g:if test="${user.photo}">
<img alt="User Photo" src="${createLink(controller:'profile', action:'profile_image', id:user.userId)}" />
</g:if>
</div>
ProfileController:
def uploadPhoto = {
def user = userService.getUser(authenticateService.principal())
def f = request.getFile('photo')
user.setPhoto(f.getBytes())
if (!user.save()) {
//doesn´t matter now
return;
}
redirect(action: 'index', model:[user: user])
}
def profile_image = {
def user = userService.getUser(params.id)
if (!user) {
response.sendError(404)
return;
}
response.setContentType(user.photo.contentType())//'image/png', 'image/jpeg', 'image/gif'
response.setContentLength(user.photo.size())
OutputStream out = response.getOutputStream();
out.write(user.photo);
out.close();
}
FYI: The picture is saved on DB correctly, I can see it, but I can´t show it on my gsp.
Any idea?
Thanks a lot guys,
Use blob type in the mapping :).
I'm stumped on an image issue... heres the lowdown.
In my layout i have an image that acts as a logo... however in the admin view there is the ability to upload a new logo and it simply replaces the current one with the exact same name. After the postback the image does not change on the layout to the updated image even though the updated image is saved. If I refresh the page with ctrl and F5, cache is gone and I can see the new image but I need it to be more automated.
Heres my img tag in the layout
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")" id="ClientLogo" alt="" width="227" height="130" style="float: left;" />
Heres the admin View
#using (Html.BeginForm("Admin", "Home", FormMethod.Post, new { #encType = "multipart/form-data" }))
{
<fieldset>
<legend>Logo Management</legend>
<p>
<input type="file" name="FileUpload" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</fieldset>
}
And finally the action
[Authorize]
[HttpPost]
public ActionResult Admin()
try
{
HttpPostedFileBase file = Request.Files[0];
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/themes/base/images"), fileName);
file.SaveAs(path);
System.IO.File.Delete(Path.Combine(Server.MapPath("~/Content/themes/base/images"), "Client_Logo.jpg"));
System.IO.File.Move(Path.Combine(Server.MapPath("~/Content/themes/base/images"), fileName), Path.Combine(Server.MapPath("~/Content/themes/base/images"), "Client_Logo.jpg"));
}
else
{
ModelState.AddModelError("uploadError", "There is a problem uploading the file.");
}
}
catch (Exception e)
{
ModelState.AddModelError("uploadError", e);
}
return View();
What does everyone suggest to do in order to refresh the image in the layout when the view is returned after uploading the image?
Cheers.
The quickest fix I can think of is displaying your logo with something random so the client would never hit the cache like:
"/images/yourlogo.png?version=123455634"
Replacing 123455634 with something always random.
Since the url of your picture will never be the same, the picture will always be downloaded.
You can mess with the cache headers for this particular file but this is the quickest fix I can think of.
Hope this helps.
EDIT try this:
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg?version=" + DateTime.Now.Ticks.ToString())" id="ClientLogo" alt="" width="227" height="130" style="float: left;" />
Well, you could set caching headers on that file NOT to cache in your web.config but that isn't ideal.
How about some jQuery?
In your Layout:
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")" id="ClientLogo" alt="" width="227" height="130" style="float: left;" data-src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")"/>
In your view that you want to change the image:
<script type="text/javascript">
$(function(){
$('#ClientLogo').attr('src',$('#ClientLogo').data('src') + '?t=' + new Date().getTime());
});
</script>
I have implemented a modal popup using an IFrame. I use some javascript to hide the main content (Popup2_Panel1) and display a loading message (Popup2_Panel2) while the IFrame is loading. When the IFrame has finished loading (iframe's onload event) I hide the loading message and unhide the main content (with IFrame). This works in IE/Safari/Chrome/Opera, but in FF the IFrame content is blank after the main content is made visible.
How I can make this work in FireFox? If I leave out the hide/show code then the IFrame is visible in FireFox, but I don't really want to show the content before the iframe has loaded new content, otherwise we see the old content momentarily.
Here is my code:
<script type="text/javascript">
function ShowPopup(srcUrl, titleCaption, width, height) {
var frame = document.getElementById("Popup2_Frame");
// This code causes the IFrame to be blank in FireFox
document.getElementById("Popup2_Panel1").style.display = "none";
document.getElementById("Popup2_Panel2").style.display = "";
frame.width = width + "px";
frame.height = height + "px";
var title = document.getElementById('Popup2_Caption');
if (title) {
title.innerHTML = titleCaption;
}
frame.src = srcUrl;
var mpe = $find('Popup2_MPE');
if (mpe) {
mpe.show();
}
}
function PopupLoaded(frame) {
// This code causes the IFrame to be blank in FireFox
document.getElementById("Popup2_Panel1").style.display = "";
document.getElementById("Popup2_Panel2").style.display = "none";
var mpe = $find('Popup2_MPE');
if (mpe) {
mpe._layout();
}
}
</script>
<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="ImgButton13" PopupControlID="Popup2_Window" BackgroundCssClass="popupModalBackground" OkControlID="Popup2_OK" CancelControlID="Popup2_Cancel" Drag="True" PopupDragHandleControlID="Popup2_Titlebar" BehaviorID="Popup2_MPE">
</asp:ModalPopupExtender>
<div id="Popup2_Window" class="popupWindow" style="display: none;">
<div id="Popup2_Panel1">
<div id="Popup2_Titlebar" class="popupTitlebar">
<span id="Popup2_Caption">Caption</span>
<img id="Popup2_ImgClose" runat="server" style="float: right; cursor: pointer;" src="~/Masters/_default/img/delete.png" alt="Close" onclick="javascript:document.getElementById('MainContent_Popup2_Cancel').click()" />
</div>
<div class="popupContent">
<iframe id="Popup2_Frame" class="popupFrame" frameborder="0" onload="PopupLoaded(this)"></iframe>
</div>
<div class="tasks">
<Exhibitor:ImgButton ID="Popup2_OK" runat="server" CssClass="icon" Text="OK" ImgSrc="~/Masters/_default/img/action-yes.png" />
<Exhibitor:ImgButton ID="Popup2_Cancel" runat="server" CssClass="icon" Text="Cancel" ImgSrc="~/Masters/_default/img/action-no.png" />
</div>
</div>
<div id="Popup2_Panel2" class="popupLoading">
<center>
Loading...<br />
<br />
<asp:Image ID="Popup2_ImgLoading" runat="server" ImageUrl="~/Masters/_default/img/loading.gif" />
</center>
</div>
</div>
The solution is to use:
frame.style.visibility = "hidden";
...
frame.style.visibility = "visible";
instead of
frame.style.display = "none";
...
frame.style.display = "";
It appears FireFox will not display the IFRAME contents at all after setting display="none" and then trying to set display="", even though it appears to be loading the URL in the background. If we set visibility to hidden the element is hidden but still takes up space so we have to do some additional juggling to give it a zero size while loading.