In my VB project i already have functions in place for retrieving every image path in a specified directory, I then use
Dim Pics() As String = piccom.GetPictures("The\Dir")
For Each pic In Pics
If Not pic = "" Then
Dim bmp As New Bitmap(pic)
Dim Width As Integer = bmp.Width
Dim Height As Integer = bmp.Height
Else
Exit For
End If
Next
to loop through all the returned images, thing is I need to be able to display these images at run time in the main content of the page, how can I display said images at runtime?
EDIT:
I went out on a whim and tried this
For Each pic In Pics
If Not pic = "" Then
Dim bmp As New Bitmap(pic)
Dim Width As Integer = bmp.Width
Dim Height As Integer = bmp.Height
Response.ContentType = "image/jpeg"
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
Else
Exit For
End If
Next
Now this actually got me closer to what i want, but instead of displaying the page with the images nested in it it just streamed the first image it grabbed to my browser - not quite what i was after. I want all the images nested in the pre-existing content box on the page.
try this:
Dim Pics() As String = piccom.GetPictures("The\Dir")
For Each pic In Pics
If Not pic = "" Then
Dim bmp As New Bitmap(pic)
Dim Width As Integer = bmp.Width
Dim Height As Integer = bmp.Height
picImage.Image = bm
picImage.SizeMode = PictureBoxSizeMode.AutoSize
Else
Exit For
End If
Next
Finally got it working in the end, first I created a new page called 'image.aspx', and put this in it
Imports System.Drawing
Imports System.Drawing.Drawing2D
Public Class image
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim query As String = Request.QueryString("i")
Dim maxw As String = Request.QueryString("maxw")
Dim maxh As String = Request.QueryString("maxh")
If Not query = "" Then
Dim file = AppDomain.CurrentDomain.BaseDirectory + "\DIRWHEREPICTURESARE" + query
Dim bmp As New Bitmap(file)
Response.ContentType = "image/jpeg"
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
End Sub
End Class
I then created a repeater in my page, with an object template like so
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="<%#Container.DataItem%>"/><br />
</ItemTemplate>
</asp:Repeater>
and in the code behind put
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Pics() As String = piccom.GetPictures("Image\Directory")
Dim aList = From fileName In Pics
Repeater1.DataSource = aList
Repeater1.DataBind()
End Sub
Hope this helps anyone who runs into this problem!
Related
I am using Visual Basic code:
Openfiledialog > I want to keep using this.
CheckedListBox
Textbox
Picturebox
My code below is working but I want the CheckedListBox to show only the filename(safefilename) for each image.jpg item from folder and show the fullpath with filename for each CheckedListBox.item selected to show in my textbox, I don't know and can't find the right code for this.
(now I am using the fullpath aka openfiledialog1.filenames) somehow I need to combine the openfiledialog.safefilenames with openfiledialog.filenames..
my code sofar:
Private Sub Button1_Click(sender As Object, e As
EventArgs) Handles Button1_Click
openFiledialog1.Filter = "Pictures(*.jpg*)|*.jpg"
If openFiledialog1.ShowDialog =
Windows.Forms.DialogResult.OK Then
For Each f As String In openFiledialog1.FileNames
SuspendLayout()
CheckedListBox1.Items.Add(f.ToString)
ResumeLayout()
TextBox1.Text = f
For i As Integer = 0 To
CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i,True)
Next
end if
Private Sub
CheckedListBox1_SelectedIndexChanged(sender As
Object, e As EventArgs) Handles
CheckedListBox1.SelectedIndexChanged
TextBox1.Text = CheckedListBox1.SelectedItem
If Not CheckedListBox1.SelectedIndex < 0 Then
Try
Dim img As Image =
Image.FromFile(CheckedListBox1.
SelectedItem.ToString())
PictureBox1.BackgroundImage = img
Catch ex As Exception
End Try
End If
I am trying to understand why this code stores a solid black image instead of the picture I'm trying to upload (i.e. the image is never stored, just a black box with the same measurements as the picture I'm uploading)?
Protected Sub btn_FileUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_FileUpload.Click
If FileUpload1.HasFile Then
Dim FileExtension As String = Path.GetExtension(FileUpload1.FileName.ToLower())
Dim allowedExtensions As String() = {".png", ".jpeg", ".jpg", ".gif"}
If Not FileUpload1.FileContent.Length > "1024000" Then
For i As Integer = 0 To allowedExtensions.Length - 1
If FileExtension = allowedExtensions(i) Then
Try
SaveImageFile(FileUpload1, Server.MapPath("~/Profile/ImageBank/Temp/image-" & GetStubs.GetUserGuid(HttpContext.Current.User.Identity.Name.ToString()) & ".jpg"), "600")
Response.Redirect(Utilities.Helpers.ResolveUrl("~/MyProfile.aspx?tab=crop"))
Catch ex As Exception
lblError.Text = "Bilden kunde inte laddas upp." + ex.Message.ToString()
End Try
End If
Next
Else
lblError.Text = "Filen du försöker att ladda upp är större en 1 Mb. Välj en annan bild eller spara bilden i ett annat filformat."
End If
End If
End Sub
Public Shared Sub SaveImageFile(ByVal clientFile As FileUpload, ByVal saveImagePath As String, ByVal maxImageWidth As Integer)
Dim sourceImage As New Bitmap(clientFile.PostedFile.InputStream)
' Resize if source image width is greater than the max:
If sourceImage.Width > maxImageWidth Then
Dim newImageHeight As Integer = CInt(sourceImage.Height * (CSng(maxImageWidth) / CSng(sourceImage.Width)))
Dim resizedImage As New Bitmap(maxImageWidth, newImageHeight)
' Save the resized image:
resizedImage.Save(saveImagePath, ImageFormat.Jpeg)
resizedImage.Dispose()
Else
' Save the source image (no resizing necessary):
sourceImage.Save(saveImagePath, ImageFormat.Jpeg)
sourceImage.Dispose()
End If
End Sub
And this is the form...
<asp:FileUpload ID="FileUpload1" runat="server" />
<span class="button-field">
<asp:Button ID="btn_FileUpload" runat="server" Text="Ladda upp" OnClick="btn_FileUpload_Click" />
</span>
<asp:Label ID="lblError" CssClass="red" runat="server"></asp:Label>
Do you have any good ideas?
I'd assume that you are uploading either a gif or a png. gif and png support transparency, but jpeg does not. The transparency/alpha channel from the gif/png file stores as black when saving as a jpeg.
To retain transparency/alpha channel and clarity, save the images as their original file types.
I solved this by changing the SaveImageFile method into this:
Public Shared Sub SaveImageFile(ByVal clientFile As FileUpload, ByVal saveImagePath As String, ByVal maxImageWidth As Integer)
Dim sourceImage As New Bitmap(clientFile.PostedFile.InputStream)
' Resize if source image width is greater than the max:
If sourceImage.Width > maxImageWidth Then
Dim newImageHeight As Integer = CInt(sourceImage.Height * (CSng(maxImageWidth) / CSng(sourceImage.Width)))
Dim resizedImage As New Bitmap(sourceImage, maxImageWidth, newImageHeight)
Dim canvas As Graphics = Graphics.FromImage(resizedImage)
' Save the resized image:
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic
canvas.DrawImage(resizedImage, New Point(0, 0))
resizedImage.Save(saveImagePath, ImageFormat.Jpeg)
resizedImage.Dispose()
Else
' Save the source image (no resizing necessary):
sourceImage.Save(saveImagePath, ImageFormat.Jpeg)
sourceImage.Dispose()
End If
End Sub
Thank you #Andrew Morton and #pasty for pointing this out to me. :)
I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
Working over 5 hours on the following problem:
Private Sub ModulEdit_PreInit(sender As Object, e As EventArgs) Handles Me.PreInit
Dim modulid As Integer = 1
loadeditors(modulid)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Sub loadeditors(modulID As Integer)
PlaceHolder1.Controls.Clear()
Using dbContext As New EntitiesModel()
Dim mps As List(Of ef.Modulparameter) = dbContext.Modulparameters.Where(Function(c) c.ModulID = modulID).ToList
Dim mmid As Int16
If EditMode.Checked = True Then
mmid = RadComboBox3.SelectedValue
End If
Dim mp As ef.Modulparameter
For Each mp In mps
Dim lbl As New Label
lbl.Text = "<BR>" & mp.Name & "<BR>"
PlaceHolder1.Controls.Add(lbl)
Select Case mp.Editor.Name
Case "textbox1line"
Dim con As New TextBox
con.ID = mp.ID
If EditMode.Checked = True Then
Using dbContext2 As New EntitiesModel
Try
Dim mpa As ef.Menu_modul_paramvalue = dbContext2.Menu_modul_paramvalues.Where(Function(c) c.ModulparameterID = mp.ID And c.Menu_modulID = mmid).First
con.Text = mpa.Valuestring
Catch ex As Exception
con.Text = "AAAA"
End Try
End Using
End If
PlaceHolder1.Controls.Add(con)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(Panel1, con, Nothing)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(con, con, Nothing)
Case "radeditor"
Dim con As New RadEditor
con.ID = mp.ID
con.ToolsFile = "\admin\controls\ToolsFile.xml"
'con.CssFiles.Add("\Content\frenzy\css\frenzy-orange.css")
If EditMode.Checked = True Then
Using dbContext2 As New EntitiesModel
Try
Dim mpa As ef.Menu_modul_paramvalue = dbContext2.Menu_modul_paramvalues.Where(Function(c) c.ModulparameterID = mp.ID And c.Menu_modulID = mmid).First
con.Content = mpa.Valuestring
Catch ex As Exception
con.Content = "BBBB"
End Try
End Using
End If
PlaceHolder1.Controls.Add(con)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(Panel1, con, Nothing)
'RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(con, con, Nothing)
End Select
Next
End Using
End Sub
I add the control dynamicly, calling the codepart above in pre_init (tryed in load and init too with same result)
The value (text) for the control is there until that line PlaceHolder1.Controls.Add(con)
After the con.text is empty.
The control is added after, but with no value.
Strange, that in the same proc i add another control (label), where the text value is on the page after.
Adding additional info:
the control value (text or content), when debugging the LoadEditors), is allways correctly set. But then on the page both (textbox and radeditor) are empty
The routing is called from pre init, as described in a lot of related posts.
You are calling loadeditors in ModulEdit_Init. Shouldn't this be LoadControls ?
I fixed it myself:
Adding "con.ViewStateMode = System.Web.UI.ViewStateMode.Disabled" before adding control to placeholder
Calling "loadeditors()" in RadComboBox3 too
much probably the problem was, that i loaded editors in page-load or init, which got the correct values, but then the RadComboBox3.SelectedIndexChanged event was called, which overwrote the values somehow
So my answer is not a real answer, but it works now (I hate such: it works, but i dont know why) ;)
i have a web application for video uploading,In that i want to show the video in the link click.i wrote a function for to show the video.i want to pass the id of video into the function .How can i Do that?
Can any one help Me?
This is my code
Private Function
GetSpecificVideo(ByVal i As Object) As
DataTable
'pass the id of the video
Dim connectionString As String =
ConfigurationManager.ConnectionStrings("UploadConnectionString")
.ConnectionString
Dim adapter As New SqlDataAdapter("SELECT FileName,
FileID,FilePath " + "FROM FileM WHERE
FileID = #FileID", connectionString)
adapter.SelectCommand.Parameters.Add("#FileID",
SqlDbType.Int).Value = DirectCast(i, Integer)
Dim table As New DataTable()
adapter.Fill(table)
Return table
End Function
Protected Sub ButtonShowVideo_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ButtonShowVideo.Click
Repeater1.DataSource = GetSpecificVideo(****here i want to get the ID****)
'the video id (2 is example)
Repeater1.DataBind()
End Sub
of the many ways one is to set CommandArgument for the link (or rather button as your code seems).
ASPX:
<ItemTemplate>
<asp:LinkButton ID="lnkVideo" runat="server"
CommandArgument='<%# Eval("VideoID")%>'
OnClick="ButtonShowVideo_Click">Watch Video</asp:LinkButton>
</ItemTemplate>
Code:
private sub void GetVideos()
'GET VIDEO(S)
'CREATE LINKS OR IF IN GRID GET LINKS AND SET COMMAND ARGUMENT FOR IT
lnk1.CommandArgument = ID_OF_VIDEO
end sub
now handle click:
Protected Sub ButtonShowVideo_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ButtonShowVideo.Click
var btn = sender as Button 'or Link or LinkButton
if(btn is not null) then
if(NOT string.IsNullOrEmpty(btn.CommandArgument)) then
var vid = Convert.ToInt32(btn.CommandArgument)
Repeater1.DataSource = GetSpecificVideo(vid)
Repeater1.DataBind()
end if
end if
End Sub