This is my first post and I'm really frustrated using Silverlight just because I'm a newbie in this.
I have three Silverlight UI (StackPanels basically) "stkMain1", "stkMain2" and "stkMain3".
I have to convert these three stack panels to PDF. I'm using silverPDF (I guess it further uses iTextSharp and PDFSharp.)
I've written the following code :
Private Sub cmdImage_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles cmdImage.Click
Dim d As New SaveFileDialog()
d.Filter = "PDF file format|*.pdf"
' Save the document...
If d.ShowDialog() = True Then
stkMain.Children.Clear()
stkMain.Children.Add(stkMain1)
Dim document As New PdfDocument()
Dim page As PdfPage = document.AddPage
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim img As ImageTools.ExtendedImage = BillPage1.ToImage
Dim mstream As New MemoryStream()
Dim encoder As New JpegEncoder()
encoder.Encode(img, mstream)
mstream.Seek(0, SeekOrigin.Begin)
Dim pdfImg As XImage = XImage.FromStream(mstream)
gfx.DrawImage(pdfImg, 0, 0)
End If
End Sub
This does everything correct and gives one PDF file with one page.. Superb output and Thumbs up.
Now the real problem starts:
Private Sub cmdImage_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles cmdImage.Click
Dim d As New SaveFileDialog()
d.Filter = "PDF file format|*.pdf"
' Save the document...
If d.ShowDialog() = True Then
stkMain.Children.Clear()
stkMain.Children.Add(BillPage1)
Dim document As New PdfDocument()
Dim page As PdfPage = document.AddPage
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim img As ImageTools.ExtendedImage = BillPage1.ToImage
Dim mstream As New MemoryStream()
Dim encoder As New JpegEncoder()
encoder.Encode(img, mstream)
mstream.Seek(0, SeekOrigin.Begin)
Dim pdfImg As XImage = XImage.FromStream(mstream)
gfx.DrawImage(pdfImg, 0, 0)
document.Pages.Add()
Dim page1 As PdfPage = document.AddPage
Dim gfx1 As XGraphics = XGraphics.FromPdfPage(page1)
Dim img1 As ImageTools.ExtendedImage = BillPage2.ToImage
Dim mstream1 As New MemoryStream()
Dim encoder1 As New JpegEncoder()
encoder1.Encode(img1, mstream1)
mstream1.Seek(0, SeekOrigin.Begin)
Dim pdfImg1 As XImage = XImage.FromStream(mstream1)
gfx1.DrawImage(pdfImg1, 0, 0)
document.Save(d.OpenFile())
End If
End Sub
Now this creates Two pages, and I get a scrambled output, contents of the stackpanels overlapping each other.
How to solve this?? I NEED HELP DESPERATELY. THE PROJECT IS DUE AND I HAVE TO SUBMIT IT BY 26th March 2011 (MONDAY).
Thanks in advance
Ravi
Try this:
If d.ShowDialog() = True Then
Dim document As New PdfDocument()
Dim page As PdfPage = document.AddPage
Dim pdfImg As XImage = DrawUI(stkMain1)
gfx.DrawImage(pdfImg, 20, 20)
page = document.AddPage()
gfx = XGraphics.FromPdfPage(page)
pdfImg = DrawUI(stkMain2)
page = document.AddPage()
gfx = XGraphics.FromPdfPage(page)
gfx.DrawImage(pdfImg, 20, 20)
pdfImg = DrawUI(stkMain3)
gfx.DrawImage(pdfImg, 20, 20)
document.Save(d.OpenFile())
End If
Private Function DrawUI(ByVal oControl As Object) As XImage
Dim img As ImageTools.ExtendedImage = ImageExtensions.ToImage(oControl)
Dim mstream As New MemoryStream()
Dim encoder As New JpegEncoder()
encoder.Encode(img, mstream)
mstream.Seek(0, SeekOrigin.Begin)
Dim pdfImg As XImage = XImage.FromStream(mstream)
Return pdfImg
End Function
Related
I inserted an image into a .mdb database with this code from my WPF app :
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & GetCurrentDirectory() & "\Data\rctts.mdb;Jet OLEDB:Database Password=arn33423342;")
con.Open()
Dim cmd As New OleDbCommand("Insert into recents(Uname,Pic,Email)values(#uname,#pic,#email)", con)
image1.Source = New BitmapImage(New Uri("D:\logo.png"))
Dim buffer As Byte()
Dim bitmap = TryCast(image1.Source, BitmapSource)
Dim encoder = New PngBitmapEncoder()
encoder.Frames.Add(BitmapFrame.Create(bitmap))
Using stream = New MemoryStream()
encoder.Save(stream)
buffer = stream.ToArray()
End Using
cmd.Parameters.AddWithValue("#pic", buffer)
The Pic column or cell's data type is OLE Object...Anyway,after inserting the data,i opened my database,i saw that a new record was added but the value of the Pic column was Long binary data.Anyway,then i went on retrieving the image in my wpf app.I used this code ?
Dim cmd As New OleDbCommand("Select * from recents", con)
Dim table As New DataTable
Dim adap As New OleDbDataAdapter(cmd)
adap.Fill(table)
If table.Rows.Count <= 0 Then
Else
For Each row In table.Rows
recentbtn.Image.ImageSource = BytesToImage(CType(row(1), Byte()))
recentbtn.Names.Text = table.Rows(0)(0).ToString
AddHandler recentbtn.MouseDown, AddressOf recentbtn_mousedow
RecentsList.stp.Children.Add(recentbtn)
Next
End If
loadingrecents.Visibility = Visibility.Hidden
End Sub
Private Shared Function BytesToImage(ByVal bytes As Byte()) As BitmapImage
Dim bm = New BitmapImage()
Using stream As MemoryStream = New MemoryStream(bytes)
stream.Position = 0
stream.Seek(0, SeekOrigin.Begin)
bm.BeginInit()
bm.StreamSource = stream
bm.CreateOptions = BitmapCreateOptions.PreservePixelFormat
bm.CacheOption = BitmapCacheOption.OnLoad
bm.EndInit()
End Using
Return bm
End Function
But it's returning an error : No imaging component suitable to complete the operation was found
Fixed it...For anyone who faces this error in future :
Make sure you're inserting the data in the proper way(sometimes corrupted data in the db causes such errors)
2 . You don't need to do some heavy coding to convert the image to byte!
Finally,let's code :
Public Sub read()
con.Open()
Dim cmd As New OleDbCommand("Select * from recents", con)
Dim _dr As OleDbDataReader
_dr = cmd.ExecuteReader
Dim _photo As Byte()
While _dr.Read()
Try
_photo = CType(_dr(1), Byte())
Dim strm As MemoryStream = New MemoryStream(_photo)
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(strm)
Dim bi As BitmapImage = New BitmapImage()
bi.BeginInit()
Dim ms As MemoryStream = New MemoryStream()
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
ms.Seek(0, SeekOrigin.Begin)
bi.StreamSource = ms
bi.EndInit()
image1.Source = bi
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End While
I am tired to make the search engine to run. Just I want to make search by image in my SQL Server database by making a choice of the column with same image.
I tried to make it with this code:
cmd = New SqlCommand("select * from TBL_Image Where Image = " & Image, sqlcon)
Can anyone help me?
Picture of Project
This is my code
Imports System.Data.SqlClient
Imports System.IO
Imports System.Drawing.Image
Public Class Form1
Dim sqlcon As New SqlConnection("server=.\MOHAMED; database=DB_Image;
integrated security = true")
Dim cmd As SqlCommand
Sub selectImage(ByVal Image As Image)
cmd = New SqlCommand("select * from TBL_Image Where Image = " & Image, sqlcon)
sqlcon.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
dr.Read()
txtShow.Text = dr(0)
Dim sora2() As Byte = CType(dr(1), Byte())
Dim ms2 As New MemoryStream(sora2)
pbox3.Image = Image.FromStream(ms2)
dr.Read()
Dim sora3() As Byte = CType(dr(1), Byte())
Dim ms3 As New MemoryStream(sora3)
pbox4.Image = Image.FromStream(ms3)
dr.Read()
Dim sora4() As Byte = CType(dr(1), Byte())
Dim ms4 As New MemoryStream(sora4)
pbox5.Image = Image.FromStream(ms4)
dr.Read()
Dim sora5() As Byte = CType(dr(1), Byte())
Dim ms5 As New MemoryStream(sora5)
pbox6.Image = Image.FromStream(ms5)
dr.Read()
Dim sora6() As Byte = CType(dr(1), Byte())
Dim ms6 As New MemoryStream(sora6)
pbox7.Image = Image.FromStream(ms6)
dr.Read()
Dim sora7() As Byte = CType(dr(1), Byte())
Dim ms7 As New MemoryStream(sora7)
pbox8.Image = Image.FromStream(ms7)
sqlcon.Close()
dr.Close()
End Sub
Private Sub btnBrowse1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse1.Click
ofd1.Filter = "All Images |*.PNG; *.JPG; *.BMP; *.GIF; *.JPEG"
If ofd1.ShowDialog = DialogResult.OK Then
pbox1.Image = Image.FromFile(ofd1.FileName)
End If
End Sub
Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
cmd = New SqlCommand("Insert into TBL_Image(Description, Image) values(#Description, #Image)", sqlcon)
cmd.Parameters.Add(New SqlParameter("#Description", SqlDbType.Text)).Value = txtDescription.Text
Dim ms1 As New MemoryStream
pbox1.Image.Save(ms1, pbox1.Image.RawFormat)
Dim Image() As Byte = ms1.ToArray
cmd.Parameters.Add(New SqlParameter("#Image", SqlDbType.Image)).Value = Image
sqlcon.Open()
cmd.ExecuteNonQuery()
sqlcon.Close()
MsgBox("Added successfully")
End Sub
Private Sub btnBrowse2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse2.Click
ofd2.Filter = "All Images |*.PNG; *.JPG; *.BMP; *.GIF; *.JPEG"
If ofd2.ShowDialog = DialogResult.OK Then
pbox2.Image = Image.FromFile(ofd2.FileName)
End If
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim msnew As New MemoryStream
pbox2.Image.Save(msnew, pbox2.Image.RawFormat)
Dim Image() As Byte = msnew.ToArray
selectImage(pbox2.Image)
End Sub
End Class
I'm using vb.net and sql server 2008 and a picturebox for uploading photos.
This is what I want to do.
1.The image can be anything. It can be bitmap,jpg,png, anything
2. upload image from my computer
3. Crop the image and resize it to fit in my picture box.
4. Save it to the SQL Server database
This is my working code for uploading and saving images in the database.
Public Class Form1
Dim a As New OpenFileDialog
Private Sub PictureBox1_DoubleClick(sender As Object, e As EventArgs) Handles PictureBox1.DoubleClick
Dim picl as string
a.filter = nothing
picl = a.filename
a.showdialog()
picturebox1.image = image.fromfile(a.filename)
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
cn.Open()
Using cmd As New SqlClient.SqlCommand("dbo.uspAdd", cn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlClient.SqlParameter("#customerPic", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
cmd.ExecuteNonQuery()
MsgBox("Save Record New record Successfully")
End Using
cn.close
End Sub
I have read some reference here but it does not work for me and now I'm stuck for almost an hour.
This is what i have tried.
Imports System.Drawing.Drawing2D
Public Class Form1
Dim a As New OpenFileDialog
Private Sub PictureBox1_DoubleClick(sender As Object, e As EventArgs) Handles PictureBox1.DoubleClick
Dim picl As String
a.Filter = Nothing
picl = a.FileName
a.ShowDialog()
PictureBox1.Image = Image.FromFile(a.FileName)
Dim OriginalImage = Image.FromFile(a.FileName)
Dim CropRect As New Rectangle(100, 0, 100, 100)
Dim CropImage = New Bitmap(CropRect.Width, CropRect.Height)
Using grp = Graphics.FromImage(CropImage)
grp.DrawImage(OriginalImage, New Rectangle(0, 0, CropRect.Width, CropRect.Height), CropRect, GraphicsUnit.Pixel)
OriginalImage.Dispose()
End Using
End Sub
Can someone please help me to fix my code. Any help would be very much appreciated. Thanks
you can crop image and designate the path and the name of cropped image with the following code sample , anyway ur sql fucntion needs image file path
Dim LocX = 100 'x cord. of where crop starts
Dim LocY = 0 'y cord. of where crop starts
Dim CropW = 100 'Crop width
Dim CropH = 100 'Crop height
Dim CropRect As New Rectangle(LocX, LocY, CropW, CropH)
Dim OriginalImage = PictureBox1.Image
Dim CropImage = New Bitmap(CropRect.Width, CropRect.Height)
Using grp = Graphics.FromImage(CropImage)
grp.DrawImage(OriginalImage, New Rectangle(0, 0, CropRect.Width, CropRect.Height), CropRect, GraphicsUnit.Pixel)
CropImage.Save("cropped file path and name here")
End Using
The code below is throwing error:
System.Runtime.InteropServices.COMException: Exception from HRESULT:
0x80072EE4
on code line:
Dim bdDecoder As BitmapDecoder = BitmapDecoder.Create(streamPhoto, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None)
Why? The requested URL exists and returns a 200. Google is not helping on this one.
Private Sub ResizeAndSave(ByVal imageURL As String)
Dim imgRequest As WebRequest = WebRequest.Create(imageURL)
Dim imgResponse As WebResponse = imgRequest.GetResponse()
Dim strThumbnail As String = "success.png"
Dim streamPhoto As Stream = imgResponse.GetResponseStream()
Dim memStream As New MemoryStream
streamPhoto.CopyTo(memStream)
Dim bfPhoto As BitmapFrame = ReadBitmapFrame(memStream)
Dim nThumbnailSize As Integer = 200, nWidth As Integer, nHeight As Integer
If bfPhoto.Width > bfPhoto.Height Then
nWidth = nThumbnailSize
nHeight = CInt(bfPhoto.Height * nThumbnailSize / bfPhoto.Width)
Else
nHeight = nThumbnailSize
nWidth = CInt(bfPhoto.Width * nThumbnailSize / bfPhoto.Height)
End If
Dim bfResize As BitmapFrame = FastResize(bfPhoto, nWidth, nHeight)
Dim baResize As Byte() = ToByteArray(bfResize)
Dim saveToPath As String = Server.MapPath(ConfigurationManager.AppSettings("products_photospath")) + "\49\" + strThumbnail
File.WriteAllBytes(saveToPath, baResize)
Console.WriteLine("Resize done!!!")
End Sub
Private Shared Function FastResize(bfPhoto As BitmapFrame, nWidth As Integer, nHeight As Integer) As BitmapFrame
Dim tbBitmap As New TransformedBitmap(bfPhoto, New ScaleTransform(nWidth / bfPhoto.Width, nHeight / bfPhoto.Height, 0, 0))
Return BitmapFrame.Create(tbBitmap)
End Function
Private Shared Function ToByteArray(bfResize As BitmapFrame) As Byte()
Using msStream As New MemoryStream()
Dim pbdDecoder As New PngBitmapEncoder()
pbdDecoder.Frames.Add(bfResize)
pbdDecoder.Save(msStream)
Return msStream.ToArray()
End Using
End Function
Private Shared Function ReadBitmapFrame(streamPhoto As Stream) As BitmapFrame
Dim bdDecoder As BitmapDecoder = BitmapDecoder.Create(streamPhoto, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None)
Return bdDecoder.Frames(0)
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ResizeAndSave("http://cdn2.emobassets.eu/media/catalog/product/1/1/1116220.jpg")
End Sub
UPDATE 1
Ok, images are now saved. But the resize only works correctly on the example .png file, and NOT on the .jpg file.
The Dell logo is saved in 200x199 px preserving transparancy, which is perfect.
The other file 1116220.jpgis saved in 625x441px...why is that not respecting the desired max width/height of 200px?
I checked into the code and the only difference I can spot is that for the png file the dimensions are a round number:
bfPhoto.Width 2000
bfPhoto.Height 1994
After FastResize executes that becomes
bfResize.Width 200
bfResize.Height 199
Where for the jpg the dimensions are
bfPhoto.Width 982,719970703125
bfPhoto.Height 695,039978027344
After FastResize executes that becomes
bfResize.Width 200
bfResize.Height 141,119995117188
So I tried to see if it was related to that image and tried with another jpg file: https://upload.wikimedia.org/wikipedia/commons/d/d8/Square-1_solved.jpg
Where for the jpg the dimensions are
bfPhoto.Width 600
bfPhoto.Height 600
After FastResize executes that becomes
bfResize.Width
bfResize.Height
That does work, so now I know it's not related to the file being a .jpg. It seems to be related to the dimensions of image 1116220.jpg, but I don't know if I can work around that by scaling differently or in some other way...
My code:
Private Sub ResizeAndSave(ByVal maxWidth As Integer, ByVal maxHeight As Integer, ByVal imageURL As String)
Dim imgRequest As WebRequest = WebRequest.Create(imageURL)
Dim imgResponse As WebResponse = imgRequest.GetResponse()
Dim streamPhoto As Stream = imgResponse.GetResponseStream()
Dim memStream As New MemoryStream
streamPhoto.CopyTo(memStream)
memStream.Position = 0
Dim bfPhoto As BitmapFrame = ReadBitmapFrame(memStream)
Dim newWidth, newHeight As Integer
Dim scaleFactor As Double
If bfPhoto.Width > maxWidth Or bfPhoto.Height > maxHeight Then
If bfPhoto.Width > maxWidth Then
scaleFactor = maxWidth / bfPhoto.Width
newWidth = Math.Round(bfPhoto.Width * scaleFactor, 0)
newHeight = Math.Round(bfPhoto.Height * scaleFactor, 0)
End If
If newHeight > maxHeight Then
scaleFactor = maxHeight / newHeight
newWidth = Math.Round(newWidth * scaleFactor, 0)
newHeight = Math.Round(newHeight * scaleFactor, 0)
End If
End If
Dim bfResize As BitmapFrame = FastResize(bfPhoto, newWidth, newHeight)
Dim baResize As Byte() = ToByteArray(bfResize)
Dim strThumbnail As String = "success" + Date.Now.Second.ToString + ".png"
Dim saveToPath As String = Server.MapPath(ConfigurationManager.AppSettings("products_photospath")) + "\49\" + strThumbnail
File.WriteAllBytes(saveToPath, baResize)
End Sub
Private Shared Function FastResize(bfPhoto As BitmapFrame, nWidth As Integer, nHeight As Integer) As BitmapFrame
Dim tbBitmap As New TransformedBitmap(bfPhoto, New ScaleTransform(nWidth / bfPhoto.Width, nHeight / bfPhoto.Height, 0, 0))
Return BitmapFrame.Create(tbBitmap)
End Function
Private Shared Function ToByteArray(bfResize As BitmapFrame) As Byte()
Using msStream As New MemoryStream()
Dim pbdDecoder As New PngBitmapEncoder()
pbdDecoder.Frames.Add(bfResize)
pbdDecoder.Save(msStream)
Return msStream.ToArray()
End Using
End Function
Private Shared Function ReadBitmapFrame(streamPhoto As Stream) As BitmapFrame
Dim bdDecoder As BitmapDecoder = BitmapDecoder.Create(streamPhoto, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None)
Return bdDecoder.Frames(0)
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ResizeAndSave(200, 200, "https://upload.wikimedia.org/wikipedia/commons/8/82/Dell_Logo.png")
ResizeAndSave(200, 200, "http://cdn2.emobassets.eu/media/catalog/product/1/1/1116220.jpg")
End Sub
Private Sub RETRIEVE()
ListView1.Clear()
Dim imglist As New ImageList
imglist.ColorDepth = ColorDepth.Depth32Bit
ListView1.LargeImageList = imglist
ListView1.LargeImageList.ImageSize = New System.Drawing.Size(50, 50)
Dim connection As New SqlConnection("Data Source=(local);Initial Catalog=images;Integrated Security=True")
Dim userdataadpter As New SqlDataAdapter("SELECT * FROM tbl_img ", connection)
Dim userdataset As New DataSet
Dim dt_images As New DataTable
userdataadpter.Fill(userdataset, "tbl_img")
For Each dr As DataRow In dt_images.Rows
Dim img_buffer = CType(dr("image"), Byte())
Dim img_stream As New MemoryStream(img_buffer, True)
img_stream.Write(img_buffer, 0, img_stream.Length)
imglist.Images.Add(dr("image").ToString(), New Bitmap(img_stream))
img_stream.Close()
Dim lsvpaarent As New ListViewItem
lsvpaarent.Text = dr("image").ToString
lsvpaarent.ImageKey = dr("imageID").ToString
ListView1.Items.Add(lsvpaarent)
Next
end sub
Looks like you're saving images as a byte array in your database and pulling them out, putting them into a imagelist, creating your listview items, then assigning the "ImageKey" to the "ImageId" of the imagelist?
The ImageKey should refer to the index of the item in the imagelist, not some id you have in a database.
See if that works for you.