I'm using libvlcsharp to stream camera, it working normally, but I can't take snapshot while stream is playing.
Here is my code :
private void TakeScreenShot()
{
var folderPath = myServices.GetAppImageFolder();
var file = folderPath + "//abc.jpg";
var file1 = Path.Combine(folderPath, "aabbc.jpg");
MediaPlayer.TakeSnapshot(0,file,0,0);
MediaPlayer.TakeSnapshot(0, file1, 0, 0);
bool doesExist = File.Exists(file);
bool doesExist1 = File.Exists(file1);
}
I can't find image, I tried use MediaPlayer.SetVideoCallback(Lock,null,null) too, but it crash before stream start play.
TakeSnapshot return true but:
in Android, I can't find image in folder, doesExist = false.
in iOS, doesExist = true , but I can't find folder contain image.
My folder path is Environment.SpecialFolder.ApplicationData.
Related
I am struggling big time with generating QR barcodes as a byte[] or Stream (something that I can use on a XAML image source)
ZXING.NET
I've tried with Zxing.Net but I find the documentation is not great.
In fact, when installing in the xamarin forms class library I am able to compile, but as soon as I add some code to write barcodes I get a compilation error saying that
Can not resolve reference: `zxing`, referenced by `MyXamarinFormsClassLibrary`. Please add a NuGet package or assembly reference for `zxing`, or remove the reference to `Sasw.AforoPass`. 0
Something funky is going on with that library.
And I'm doing a simple example such as:
var options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 250,
Height = 250
};
var writer = new BarcodeWriter<Image>();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = options;
var result = writer.Write("foo");
MyImage.Source = result.Source;
QRCoder
It's another nuget library. I've successfully used for dotnet core applications, but it does not seem to be compatible with Xamarin Forms (or Mono, or whatever). It says that the platform is not supported. Probably because it uses System.Drawing.Common?
ZXing.Net.Mobile.Forms
I've used this other library which underneath it uses ZXing.Net. What I don't like is that I don't know if there's any way to generate qr codes without relying on Xaml or the ZXingBarcodeImageView.
I managed to generate QR Codes that way as a workaround, but I hit another wall. See https://github.com/Redth/ZXing.Net.Mobile/issues/908 in which I describe the problems I have to embed the ZXingBarcodeImageView in a carousel inside a popup.
So basically I wanted to go back to the roots, and simply have a working example with the latest version of ZXing.Net (or an alternative, if it exists) that I am able to use in Xamarin Forms.
Most of the examples I find talk about BarcodeWriter but there is no such a class anymore. There is a generic one BarcodeWriter<TUnknownType>and a BarcodeWriterGeneric but as I said, I could not compile anything using Zxing.Net library and with through ZXing.Net.Mobile the images I generate are always empty.
Any help or "modern" code sample (ideally with an alternative) would be much appreciated
UPDATE 1
In other words, I'm looking to have in Xamarin Forms something similar to this code that I had using QrCoder library.
public class QrCodeService
: IQrCodeService
{
public Stream GetQrCode(Guid id, string mimeType = "image/jpeg")
{
if (mimeType is null)
{
throw new ArgumentNullException(nameof(mimeType));
}
var qrGenerator = new QRCodeGenerator();
var qrCodeData = qrGenerator.CreateQrCode(id.ToString(), QRCodeGenerator.ECCLevel.Q);
var qrCode = new QRCode(qrCodeData);
var qrCodeImage = qrCode.GetGraphic(20);
var myImageCodecInfo = GetEncoderInfo(mimeType);
var myEncoder = Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
var stream = new MemoryStream();
qrCodeImage.Save(stream, myImageCodecInfo, myEncoderParameters);
stream.Position = 0;
return stream;
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
var encoders = ImageCodecInfo.GetImageEncoders();
foreach (var encoder in encoders)
{
if (encoder.MimeType == mimeType)
{
return encoder;
}
}
throw new KeyNotFoundException($"Encoder for {mimeType} not found");
}
}
The solution uses QrCoder library and it works fine for Xamarin Forms as follows.
private byte[] GetQrImageAsBytes()
{
var randomText = Guid.NewGuid().ToString();
var qrGenerator = new QRCodeGenerator();
var qrCodeData = qrGenerator.CreateQrCode(randomText, QRCodeGenerator.ECCLevel.L);
var qRCode = new PngByteQRCode(qrCodeData);
var qrCodeBytes = qRCode.GetGraphic(20);
return qrCodeBytes;
}
Here a working sample with this implementation
QrCoder library can do this, but instead of using as in the main page of the project:
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode("The text which should be encoded.", QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData); // This point onwards is problematic
Bitmap qrCodeImage = qrCode.GetGraphic(20); // This will throw not supported exception
Switch the last 2 lines to:
var qrCode = new PngByteQRCode(qrCodeData);
byte[] imageByteArray = qrCode.GetGraphic(20);
You'll get byte array instead, but you can convert it into Stream or whatever you like afterwards.
I scan the document with camera and write in to stream. Now is the hardest part, i need to write code for Cropping & Perspective Correction on the document taken. There is a nuget packages and libraries but they are expensive. I want to try to make my own code but don't know from where to start.
This is my code :
var file = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() {
Directory = "Sample",
Name = "test.jpg",
SaveToAlbum = false,
});
if (file == null)
return;
Stream stream = file.GetStream();
var localPath = string.Empty;
localPath = Task.Run(() => DependencyService.Get<Shared.ISharedFunction>().SaveFileToDisk(stream, "picture.jpg")).Result;
ImageDoc = ImageSource.FromStream(() => stream);
Picture.Name = localPath;
ImagesNew.Add(Picture);
This is my code i'm using media library to take photo(document) , and saving in stream. Now for the stream i need to convert in pdf(it may be more then one image). I need Cropping & Perspective Correction on the image.
My goal is to modify a .txt file in azure file storage using WindowsAzure.Storage API. I would like to know if there is any method to add some text in the file.
Is it easier to use the System.IO API?
I've already tried the cloudFileStream.Write() but it didn't work.
Thank you
The sample on https://github.com/Azure/azure-storage-net/blob/master/Test/WindowsRuntime/File/FileStreamTests.cs shows you how to do this.
public async Task FileOpenWriteTestAsync()
{
byte[] buffer = GetRandomBuffer(2 * 1024);
CloudFileShare share = GetRandomShareReference();
try
{
await share.CreateAsync();
CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
using (CloudFileStream fileStream = await file.OpenWriteAsync(2048))
{
Stream fileStreamForWrite = fileStream;
await fileStreamForWrite.WriteAsync(buffer, 0, 2048);
await fileStreamForWrite.FlushAsync();
byte[] testBuffer = new byte[2048];
MemoryStream dstStream = new MemoryStream(testBuffer);
await file.DownloadRangeToStreamAsync(dstStream, null, null);
MemoryStream memStream = new MemoryStream(buffer);
TestHelper.AssertStreamsAreEqual(memStream, dstStream);
}
}
finally
{
share.DeleteIfExistsAsync().Wait();
}
}
If you want to add some text(append to the existing data) to the file on azure file storage, there is no direct method. You need to download it and then upload with the text you want to append.
string accountName = "xxx";
string key = "xxx";
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var share = storageAccount.CreateCloudFileClient().GetShareReference("testfolder");
CloudFile file1 = share.GetRootDirectoryReference().GetFileReference("a.txt");
//if you want to append some text from local file
var stream1 = File.OpenRead("your file path in local, like d:\hello.txt");
string from_local_file = (new StreamReader(stream1)).ReadToEnd();
//if you just want to add some text from string, directly use the string
//string from_local_file ="the text I want to append to azure file";
//download the content of the azure file
string from_azure_file = file1.DownloadText();
//this does the trick like appending text to azure file, not overwrite
file1.UploadText(from_azure_file + from_local_file);
If you want to directly upload text to file stored on azure file storage, you should use one of the following methods: UploadText() / UploadFromFile() / UploadFromStream().
Note that this will overwrite the existing data in the azure file.
If you want to update the context of azure file, you can use WriteRange() method. But it has some limitations, if you're interesting about it, I can provide you some code.
Is it possible in an air application to start a download, pause it and after that resume it?
I want to download very big files (1-3Gb) and I need to be sure if the connection is interrupted, then the next time the user tries to download the file it's start from the last position.
Any ideas and source code samples would be appreciated.
Yes, you would want to use the URLStream class (URLLoader doesn't support partial downloads) and the HTTP Range header. Note that there are some onerous security restrictions on the Range header, but it should be fine in an AIR application. Here's some untested code that should give you the general idea.
private var _us:URLStream;
private var _buf:ByteArray;
private var _offs:uint;
private var _paused:Boolean;
private var _intervalId:uint;
...
private function init():void {
_buf = new ByteArray();
_offs = 0;
var ur:URLRequest = new URLRequest( ... uri ... );
_us = new URLStream();
_paused = false;
_intervalId = setInterval(500, partialLoad);
}
...
private function partialLoad():void {
var len:uint = _us.bytesAvailable;
_us.readBytes(_buf, _offs, len);
_offs += len;
if (_paused) {
_us.close();
clearInterval(_intervalId);
}
}
...
private function pause():void {
_paused = true;
}
...
private function resume():void {
var ur:URLRequest = new URLRequest(... uri ...);
ur.requestHeaders = [new URLRequestHeader("Range", "bytes=" + _offs + "-")];
_us.load(ur);
_paused = false;
_intervalId = setInterval(500, partialLoad);
}
if you are targeting mobile devices, maybe you should take a look at this native extension: http://myappsnippet.com/download-manager-air-native-extension/ it supports simultaneous resumable downloads with multi-section chunks to download files as fast as possible.
I have a custom user control that i use in a page in Umbraco CMS... since upgrading to version 4, it seems this user control wont work any longer.
The user control contains an ajax uploader control (support request post here: http://cutesoft.net/forums/53732/ShowThread.aspx#53732), which allows users to upload images, then displays the uploaded images to the user. The control and image displays are contained within an UpdatePanel, which is where this problem is - seems the data getting sent back to the updatePanel is not valid, so the client is spitting the dummy and throwing this error:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '
<!DOCTYPE html PUBL'.
I think its somethihng to do with how Master Pages is implemented in Umbraco v4 that is causing this. Any ideas as to why this may have happened, and what i can look at to try to solve it?
FYI, here's a blog post that describes the error and its possible causes:
http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx
i'm doing any Response.write or Response.Redirect in the updatePanel
I'm not using any response filters
I've disabled server trace
I'm not using response.transfer
But, regardless of the above, this works fine using the same usercontrol on an Umbraco v3 site, which leads me to believe its somethign to do with v4 that's caused this.
Any suggestions greatly appreciated
I know that this whole answer is not directly a fix for your problem, but more like a workaround. this is because I am not familiar with the custom control you use.
i will however take a look tonight at your problem and see if i can find a solution for the code and plugin you use currently.
in the mean time i might give you some idea of the ajax upload i am using myself.
i know its a big chunk of code, but if you are interested you can go for it :)
my example case
I have an upload control in my own website and it works perfectly with umbraco.
the form and upload are powered with jQuery (upload is handled by jQuery.AjaxUpload plugin)
and i created a generic handler inside my umbraco folder which handles the file on the server.
creating a media item in the media library for it (and in my case beeing an avatar uploader on your profile page, it also adds the newly created mediaitem to the member's avatar property)
jQuery code: (stored in script block in the head of your page, or in a separate script)
initializeChangeAvatarForm = function() {
var button = $('#submitChangeAvatar'), interval;
new AjaxUpload(button,{
action: '/umbraco/AjaxFileUpload.ashx',
name: 'myfile',
onSubmit : function(file, ext){
// change button text to uploading + add class (with animating background loading image)
button.text('Uploading').addClass('loading');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
},
onComplete: function(file, response){
button.text('Upload nieuw').removeClass('loading');
// Although plugins emulates hover effect automatically,
// it doens't work when button is disabled
button.removeClass('hover');
window.clearInterval(interval);
// enable upload button
this.enable();
}
});
};
$(document).ready(function(){
initializeChangeMailForm();
});
html code in your body:
<div id="container"><h2>Upload Avatar</h2><button class="button" id="submitChangeAvatar" type="button">Upload new</button></div>
jQuery ajaxupload plugin: (/scripts/jQuery.ajaxupload.js)
'since this code is too long i added a link directly to the .js file i use
'and another link to the page where i got the plugin
handler .ashx: (stored inside /umbraco/AjaxFileUpload.ashx)
using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.Xml;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.member;
namespace SH.umbServices
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class AjaxFileUpload : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string strResponse = "error";
try
{
//string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
//string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
//string strSaveLocation = context.Server.MapPath("../images/temp") + "\\" + strFileName;
//context.Request.Files[0].SaveAs(strSaveLocation);
UmbracoSave(context);
strResponse = "success";
}
catch
{
}
context.Response.ContentType = "text/plain";
context.Response.Write(strResponse);
}
public bool IsReusable
{
get
{
return false;
}
}
#region "umbMediaItem"
protected string UmbracoSave(HttpContext context)
{
string mediaPath = "";
if (context.Request.Files[0] != null)
{
if (context.Request.Files[0].FileName != "")
{
// Find filename
string _text = context.Request.Files[0].FileName;
string _ext = Path.GetExtension(context.Request.Files[0].FileName);
string filename;
string _fullFilePath;
//filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();
filename = Path.GetFileName(_text);
string _filenameWithoutExtention = filename.Replace(_ext, "");
int _p = 1212; // parent node.. -1 for media root)
// create the Media Node
umbraco.cms.businesslogic.media.Media m = umbraco.cms.businesslogic.media.Media.MakeNew(
_filenameWithoutExtention, umbraco.cms.businesslogic.media.MediaType.GetByAlias("image"), User.GetUser(0), _p);
// Create a new folder in the /media folder with the name /media/propertyid
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/../media/" + m.Id.ToString()));
_fullFilePath = System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/../media/" + m.Id.ToString() + "/" + filename);
context.Request.Files[0].SaveAs(_fullFilePath);
// Save extension
//string orgExt = ((string)_text.Substring(_text.LastIndexOf(".") + 1, _text.Length - _text.LastIndexOf(".") - 1));
string orgExt = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
orgExt = orgExt.Trim(char.Parse("."));
try
{
m.getProperty("umbracoExtension").Value = orgExt;
}
catch { }
// Save file size
try
{
System.IO.FileInfo fi = new FileInfo(_fullFilePath);
m.getProperty("umbracoBytes").Value = fi.Length.ToString();
}
catch { }
// Check if image and then get sizes, make thumb and update database
if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt + ",") > 0)
{
int fileWidth;
int fileHeight;
FileStream fs = new FileStream(_fullFilePath,
FileMode.Open, FileAccess.Read, FileShare.Read);
System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
fileWidth = image.Width;
fileHeight = image.Height;
fs.Close();
try
{
m.getProperty("umbracoWidth").Value = fileWidth.ToString();
m.getProperty("umbracoHeight").Value = fileHeight.ToString();
}
catch { }
// Generate thumbnails
string fileNameThumb = _fullFilePath.Replace("." + orgExt, "_thumb");
generateThumbnail(image, 100, fileWidth, fileHeight, _fullFilePath, orgExt, fileNameThumb + ".jpg");
image.Dispose();
}
mediaPath = "/media/" + m.Id.ToString() + "/" + filename;
m.getProperty("umbracoFile").Value = mediaPath;
m.XmlGenerate(new XmlDocument());
Member mbr = Member.GetCurrentMember();
umbraco.cms.businesslogic.property.Property avt = mbr.getProperty("memberAvatar");
avt.Value = m.Id;
mbr.XmlGenerate(new XmlDocument());
mbr.Save();
//string commerceFileName = mediaPath;
//CommerceSave(commerceFileName);
}
}
return mediaPath;
}
protected void generateThumbnail(System.Drawing.Image image, int maxWidthHeight, int fileWidth, int fileHeight, string fullFilePath, string ext, string thumbnailFileName)
{
// Generate thumbnail
float fx = (float)fileWidth / (float)maxWidthHeight;
float fy = (float)fileHeight / (float)maxWidthHeight;
// must fit in thumbnail size
float f = Math.Max(fx, fy); //if (f < 1) f = 1;
int widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f);
// fixes for empty width or height
if (widthTh == 0)
widthTh = 1;
if (heightTh == 0)
heightTh = 1;
// Create new image with best quality settings
Bitmap bp = new Bitmap(widthTh, heightTh);
Graphics g = Graphics.FromImage(bp);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// Copy the old image to the new and resized
Rectangle rect = new Rectangle(0, 0, widthTh, heightTh);
g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
// Copy metadata
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo codec = null;
for (int i = 0; i < codecs.Length; i++)
{
if (codecs[i].MimeType.Equals("image/jpeg"))
codec = codecs[i];
}
// Set compresion ratio to 90%
EncoderParameters ep = new EncoderParameters();
ep.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
// Save the new image
bp.Save(thumbnailFileName, codec, ep);
bp.Dispose();
g.Dispose();
}
#endregion
}
}
I hope this shed some light on what i use.
Pfew,..That's a lot of code.
I was only interessted in saving media in Umbraco but it's nice to see a jQuery upload too.
What upload jQuery lib your using? I've found serveral.
You could make the code a bit simpler by using Path.Combine, FileInfo.Extension merging if's and a few extra variables here an there. But hey I've got Resharper to make my live easier.