I have a problem with GifRenderer class.
In an Windows Phone 8 app, my scope is generate an animated gif starting from a list of png images stored in isolated storage of app and then save it and share it.
When in my code I call GifRenderer.RenderAsync method, I have an ArgumentException, Value does not fall within the expected range, as you can see in following VB code.
Where am I doing wrong?
Dim images = New List(Of IImageProvider)
Dim image As Picture
Try
For Each fileName In fileNames
images.Add(New StorageFileImageSource(Await StorageFile.GetFileFromPathAsync(IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, fileName))))
Next
Dim info = Await images(0).GetInfoAsync()
Using renderer = New GifRenderer()
renderer.Size = info.ImageSize
renderer.Sources = images
renderer.Duration = 1000
Dim gifBuffer = Await renderer.RenderAsync()
Dim stream = gifBuffer.AsStream()
Using library = New MediaLibrary()
Dim filename = String.Format("{0}+{1}.gif", IO.Path.GetFileNameWithoutExtension(fileNames(0)), fileNames.Count)
image = library.SavePicture(IO.Path.GetFileName(filename), stream)
End Using
End Using
Dim task = New ShareMediaTask()
task.FilePath = image.GetPath()
task.Show()
Catch ex As Exception
Debug.WriteLine(ex)
'renderer.RenderAsync() ->
'System.ArgumentException: Value does not fall within the expected range.
' at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
' at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
' at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
' at WP8.App.VB$StateMachine_0_ShareAnimation.MoveNext()
End Try
Related
I want to read 2D matrixcode from an image that I captured using camera and display it on a picturebox. The image will be saved from picturebox and then it will read the value of 2D matrixcode from the image.
I managed to read it one time. However, the second time I click the button to read it, it appeared this error. ": A generic error occurred in GDI+."
I want it able to capture it multiple time for each time I click.
Below are my attached code :
Dim filepath As String = Environment.CurrentDirectory
Dim current2 As Bitmap = CType(PictureBoxFilter.Image, Bitmap)
Dim fileName2 As String = System.IO.Path.Combine(filepath, "test.png")
current2.Save(fileName2)
Dim decoder As DmtxImageDecoder = New DmtxImageDecoder()
Dim codes As List(Of String) = decoder.DecodeImage(CType(Bitmap.FromFile(System.IO.Path.Combine(filepath, "test.png")), Bitmap), 1, New TimeSpan(0, 0, 3))
For Each code As String In codes
If code <> "" Then
Label1.Text = code
Else
Label1.Text = ""
End If
Next
codes.Clear()
current2.Dispose()
This is the modified code about uploadsession soo at small size file it working like a charm but when I try larger file like 5mb up. The following error keep showing up :
+$exception {"lookup_failed/closed/..."} System.Exception {Dropbox.Api.ApiException}
Private Async Sub UploadToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles UploadToolStripMenuItem2.Click
Dim C As New OpenFileDialog
C.Title = "Choose File"
C.Filter = "All Files (*.*)|*.*"
If C.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fileinfos = Path.GetFileName(C.FileName)
Dim filetempat = Path.GetFullPath(C.FileName)
Dim tempat As String = direktori.Text & "/" & fileinfos
Await Upload(filetempat, tempat)
End If
End Sub
Async Function Upload(localPath As String, remotePath As String) As Task
Const ChunkSize As Integer = 4096 * 1024
Using fileStream = File.Open(localPath, FileMode.Open)
If fileStream.Length <= ChunkSize Then
Await A.Files.UploadAsync(remotePath, body:=fileStream)
Else
Await Me.ChunkUpload(remotePath, fileStream, ChunkSize)
End If
End Using
End Function
Private Async Function ChunkUpload(path As [String], stream As FileStream, chunkSize As Integer) As Task
Dim numChunks As Integer = CInt(Math.Ceiling(CDbl(stream.Length) / chunkSize))
Dim buffer As Byte() = New Byte(chunkSize - 1) {}
Dim sessionId As String = Nothing
For idx As Integer = 0 To numChunks - 1
Dim byteRead = stream.Read(buffer, 0, chunkSize)
Using memStream = New MemoryStream(buffer, 0, byteRead)
If idx = 0 Then
Dim result = Await A.Files.UploadSessionStartAsync(True, memStream)
sessionId = result.SessionId
kondisi.Text=byteRead
Else
Dim cursor = New UploadSessionCursor(sessionId, CULng(CUInt(chunkSize) * CUInt(idx)))
If idx = numChunks - 1 Then
Dim fileMetadata As FileMetadata = Await A.Files.UploadSessionFinishAsync(cursor, New CommitInfo(path), memStream)
MessageBox.Show("Upload Complete")
Console.WriteLine(fileMetadata.PathDisplay)
Else
Await A.Files.UploadSessionAppendV2Async(cursor, True, memStream)
MessageBox.Show("Upload Failed")
End If
End If
End Using
Next
End Function
okay now its fixed, but when i got home, and try this code at my home,i got error, is this method are affected by slow internet connection ?.cause my campus have a decent speed.
this is the error message
+$exception {"Cannot access a disposed object.\r\nObject name: 'System.Net.Sockets.Socket'."} System.Exception {System.ObjectDisposedException}
this Cannot obtain value of local or argument '<this>' as it is not available at this instruction pointer, possibly because it has been optimized away. System.Net.Sockets.Socket
asyncResult Cannot obtain value of local or argument 'asyncResult' as it is not available at this instruction pointer, possibly because it has been optimized away. System.IAsyncResult
errorCode Cannot obtain value of local or argument 'errorCode' as it is not available at this instruction pointer, possibly because it has been optimized away. System.Net.Sockets.SocketError
this error window i got
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
Additional information: Cannot access a disposed object.
This Closed error indicates you can't continue uploading to the upload session because it's already been closed.
The UploadSessionStartAsync and UploadSessionAppendV2Async both take a bool parameter called close, which closes the session.
You're always setting that to True when you call those, closing the sessions. You shouldn't close a session until you're finished uploading data for it.
I am trying to do following things in Windows Forms
1) Read a PDF in Windows Forms
2) Get the Images with Text in it
3) Color / fill the Image
4) save everything to a new file
I have tried Problem with PdfTextExtractor in itext!
But It didn't help.
Here is the code I've tried:
Public Shared Sub ExtractImagesFromPDF(sourcePdf As String, outputPath As String)
'NOTE: This will only get the first image it finds per page.'
Dim pdf As New PdfReader(sourcePdf)
Dim raf As RandomAccessFileOrArray = New iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf)
Try
For pageNumber As Integer = 1 To pdf.NumberOfPages
Dim pg As PdfDictionary = pdf.GetPageN(pageNumber)
' recursively search pages, forms and groups for images.'
Dim obj As PdfObject = FindImageInPDFDictionary(pg)
If obj IsNot Nothing Then
Dim XrefIndex As Integer = Convert.ToInt32(DirectCast(obj, PRIndirectReference).Number.ToString(System.Globalization.CultureInfo.InvariantCulture))
Dim pdfObj As PdfObject = pdf.GetPdfObject(XrefIndex)
Dim pdfStrem As PdfStream = DirectCast(pdfObj, PdfStream)
Dim bytes As Byte() = PdfReader.GetStreamBytesRaw(DirectCast(pdfStrem, PRStream))
If (bytes IsNot Nothing) Then
Using memStream As New System.IO.MemoryStream(bytes)
memStream.Position = 0
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(memStream)
' must save the file while stream is open.'
If Not Directory.Exists(outputPath) Then
Directory.CreateDirectory(outputPath)
End If
Dim path__1 As String = Path.Combine(outputPath, [String].Format("{0}.jpg", pageNumber))
Dim parms As New System.Drawing.Imaging.EncoderParameters(1)
parms.Param(0) = New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0)
'Dim jpegEncoder As System.Drawing.Imaging.ImageCodecInfo = iTextSharp.text.Utilities.GetImageEncoder("JPEG")'
img.Save(path__1) 'jpegEncoder, parms'
End Using
End If
End If
Next
Catch
Throw
Finally
pdf.Close()
raf.Close()
End Try
End Sub
Now, the actual purpose of this is to get something like this
If this is the actual PDF, I will have to check if there any any items in that bin(by Text in that box)
If there are items then I have to color it like below
Can someone help me with this
The PDF can be retrieved here.
I am trying to upload a file using a thread. I have placed a simple file upload control and a button on a page.The code looks like this-
Protected Sub btnUpload_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles btnUpload.Click
Dim timeStart As TimeSpan = Nothing
Dim timeEnd As TimeSpan = Nothing
Dim timeDiff As TimeSpan = Nothing
Dim ex As Exception = Nothing
Dim FileNameWithoutExtension As String = String.Empty
Try
Dim objTh As Thread = Nothing
objTh = New Thread(AddressOf SaveFileByBuffering)
timeStart = DateTime.Now.TimeOfDay
objTh.IsBackground = True
FileNameWithoutExtension = System.IO.Path.GetFileName(FldUploadThreading.FileName)
objTh.Start("New_" + FileNameWithoutExtension)
objTh.Name = "ARAThreadFileBuffer"
objTh.Join()
timeEnd = DateTime.Now.TimeOfDay
timeDiff = timeEnd - timeStart
Catch exThAbort As ThreadAbortException
ex = exThAbort
Catch exTh As ThreadStartException
ex = exTh
Catch exCommon As Exception
ex = exCommon
End Try
End Sub
Method to be called using thread:
Public Function SaveFileByBuffering(ByVal lstrFilePath As String)
Dim bufferSize As Integer = 512
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim pathUrl As String = ConfigurationManager.AppSettings("strFilePath").ToString()
Dim uploadObj As UploadDetail = New UploadDetail()
uploadObj.IsReady = True
uploadObj.FileName = lstrFilePath
uploadObj.ContentLength = Me.FldUploadThreading.PostedFile.ContentLength
Me.Session("UploadXDetail") = uploadObj
Dim Upload As UploadDetail = DirectCast(Me.Session("UploadXDetail"), UploadDetail)
Dim fileName As String = Path.GetFileName(Me.FldUploadThreading.PostedFile.FileName)
Using fs As New FileStream(Path.Combine(pathUrl, lstrFilePath), FileMode.Create)
While Upload.UploadedLength < Upload.ContentLength
Dim bytes As Integer = Me.FldUploadThreading.PostedFile.InputStream.Read(buffer, 0, bufferSize)
fs.Write(buffer, 0, bytes)
Upload.UploadedLength += bytes
End While
End Using
End Function
There are two issues:
When someone clicks on the same button simultaneously the thread behavior works in a different way, some time page crashes.
When this process I have tested on multi-user environment with 60 users and file size is 25 mb each user the page crashed.
I have to use .NET 3.5 so I cannot use the advanced version of file upload in 2010 or later.
Error : 1-File uploding is more than 15 minutes but still in progress 2- Internet explorer cannot explore the page -Diagnose Internet problems 3- some user get login probem to the server on which the site has hosted
The course I usually take in .NET is to use ThreadPool.QueueUserWorkItem
If you do this with anonymous lambdas, I find it makes the syntax and life rather nice. You can do something like this:
btnUpload.Enabled = False
ThreadPool.QueueUserWorkItem(Sub()
SaveFileByBuffering(FldUploadThreading.FileName)
RaiseEvent EnableButton
End Sub)
With this event handler:
Public Sub EnableButton() Handles EnableButton
If Me.InvokeRequired Then
Me.BeginInvoke(Sub() EnableButton())
Else
btnUpload.Enabled = True
EndIf
EndSub
My .NET is rusty and I don't have a compiler anywhere, but doing something like this should handle most of your issues.
I am trying to create folder in my Dropbox using Sharpbox (the code is in vb.net).
I have a string variable named "str".
This is the code I use:
Dim dropBoxStorage = New CloudStorage()
Dim dropBoxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox)
Dim str As String = "TheNameForMyFolder"
Environment.ExpandEnvironmentVariables(myfilepath)
Dim srcFile = Environment.ExpandEnvironmentVariables(myfilepath)
dropBoxStorage.CreateFolder("/" + str)
Dim publicFolder = dropBoxStorage.GetFolder("/" + str)
dropBoxStorage.UploadFile(srcFile, publicFolder)
A exception happens:
An unhandled exception of type 'AppLimit.CloudComputing.SharpBox.Exceptions.SharpBoxException' occurred in AppLimit.CloudComputing.SharpBox.dll
The exception happened at this line:
dropBoxStorage.CreateFolder("/" + str)
What have I done wrong, and what shall I do instead?
You need to open the connection with dropBoxStorage.Open().
Good example is available on Codeplex (VB.NET)