Visualizzazione dei risultati da 1 a 7 su 7
  1. #1
    Utente di HTML.it L'avatar di Veronica80
    Registrato dal
    May 2006
    Messaggi
    2,110

    [VB.NET] - Resize e Crop di un immagine

    Ciao a tutti!
    Ho urgente bisogno di creare una funzione che mi ridimensioni una foto croppandola secondo le dimensioni che voglio io!

    Ho trovato un sacco di esempi ASP ma non Vb.NET e sinceramente non capendone nulla di ASP non son riuscita a "convertirli".

    Qualcuno può aiutarmi?

  2. #2
    Utente di HTML.it L'avatar di Veronica80
    Registrato dal
    May 2006
    Messaggi
    2,110
    ok per ora ho risolto così:

    codice:
    Private Sub ridimensiona(ByVal nomeImg As String, ByVal nomePath As String, ByVal destPath As String, ByVal wFinaleImg As Integer, ByVal hFinaleImg As Integer)
            Dim nomeCompletoImg As String = nomePath & "/" & nomeImg
            Dim IntXSize As Integer
            Dim IntYSize As Integer
            Dim IntHalfWidth As Integer
            Dim IntHalfHeight As Integer
            Dim X As Integer
            Dim Y As Integer
            Dim compressione As Long = 1
    
    
            'Variabili per l'anteprima
            Dim ObjBMP As System.Drawing.Image
            Dim ObjGraphics As System.Drawing.Image
    
            'prendiamo alcune informazioni importanti dall'immagine orginale
            ObjBMP = New Bitmap(nomeCompletoImg)
    
            'Misure dell'immagine
            Dim IntImgW As Integer = ObjBMP.Width
            Dim IntImgH As Integer = ObjBMP.Height
    
            'Nuove misure dell'immagine servono per mantenere le proporzioni, per il mio caso mi basta ridimensionare in base all'altezza
    
            Dim IntNewImgW As Integer
            Dim IntNewImgH As Integer
    
            IntNewImgH = hFinaleImg
            IntNewImgW = (hFinaleImg / IntImgH) * IntImgW
    
            ObjGraphics = ObjBMP.GetThumbnailImage(IntNewImgW, IntNewImgH, Nothing, IntPtr.Zero)
    
    
            Dim myImageCodecInfo As System.Drawing.Imaging.ImageCodecInfo
            Dim myEncoder As System.Drawing.Imaging.Encoder
            Dim myEncoderParameter As System.Drawing.Imaging.EncoderParameter
            Dim myEncoderParameters As System.Drawing.Imaging.EncoderParameters
    
    
            Dim i As Integer
            Dim encoders As System.Drawing.Imaging.ImageCodecInfo() = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
    
            For i = 0 To (encoders.Length - 1)
                If (encoders(i).MimeType = "image/jpeg") Then
                    myImageCodecInfo = encoders(i)
                End If
            Next i
    
            myEncoder = System.Drawing.Imaging.Encoder.Quality
    
            myEncoderParameters = New System.Drawing.Imaging.EncoderParameters(1)
    
            myEncoderParameter = New System.Drawing.Imaging.EncoderParameter(myEncoder, compressione)
    
            myEncoderParameters.Param(0) = myEncoderParameter
    
            ObjGraphics = ObjBMP.GetThumbnailImage(IntNewImgW, IntNewImgH, Nothing, IntPtr.Zero)
    
            'Qui viene fatto il crop, se non vi è necessario saltatelo
            Dim ObjSysDrawImg As New System.Drawing.Bitmap(wFinaleImg, hFinaleImg, PixelFormat.Format24bppRgb)
    
            Dim ObjGraphics2 As Graphics = Graphics.FromImage(ObjSysDrawImg)
    
            ObjGraphics2.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
            ObjGraphics2.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
            ObjGraphics2.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
    
            IntXSize = ObjGraphics.Width - 1
            IntYSize = ObjGraphics.Height - 1
    
            IntHalfWidth = IntXSize / 2
            IntHalfHeight = IntYSize / 2
            X = IntHalfWidth - (wFinaleImg / 2)
            Y = IntHalfHeight - (hFinaleImg / 2)
            ObjGraphics2.DrawImage(ObjGraphics, New Rectangle(0, 0, wFinaleImg, hFinaleImg), New Rectangle(X, Y, wFinaleImg, hFinaleImg), GraphicsUnit.Pixel)
            ObjGraphics.Dispose()
            '------------------------------------------------------
    
            If IO.Directory.Exists(destPath) = False Then
                IO.Directory.CreateDirectory(destPath)
            End If
            ObjSysDrawImg.Save(destPath & "\" & nomeImg, myImageCodecInfo, myEncoderParameters)
            ObjBMP.Dispose()
            ObjGraphics2.Dispose()
            ObjSysDrawImg.Dispose()
        End Sub
    Tutto funziona solo che l'immagine esce di qualità infima

    Com'è possibile? :°°°

  3. #3
    Utente di HTML.it L'avatar di Veronica80
    Registrato dal
    May 2006
    Messaggi
    2,110
    Possibile che nessuno sappia come si croppa un'immagine?

  4. #4
    Utente di HTML.it L'avatar di gibra
    Registrato dal
    Apr 2008
    residenza
    Italy
    Messaggi
    4,244
    Originariamente inviato da Veronica80
    Possibile che nessuno sappia come si croppa un'immagine?
    Prima di tutto ti chiederi cortesemente di non usare termini storpiati come 'croppa', 'croppare', 'croppandola' e così via...
    Il perchè si voglia storpiare termini stranieri mi è davvero oscuro (oltre che sbagliato).

    Oltretutto il termine crop l'hai usato a sproposito, infatti in inglese crop (in grafica) significa ritagliare, mentre tu hai scritto che vuoi ridimensionare.

    Quindi i casi sono due:
    1 - vuoi ridimensionare l'immagine
    2 - vuoi ritagliare l'immagine

    Dalla tua richiesta mi pare ovvio il primo.

    Ora, dato che, come tu stessa hai scritto, hai risolto è evidente che lo sai anche tu come si fa. Ma non è questo il punto.

    Infatti quello che lamenti è che l'immagine ridimensionata scada di qualità.

    Su questo però nessuno può farci niente perchè è quello che avviene quando si ridimensiona un'immagine raster.
    Solo le immagini vettoriali non scadono di qualità, ridimensionandole, ma a loro volta soffrono di altre problematiche.

    In sostanza, quello che chiedi è materialmente impossibile, nemmeno programmi blasonati come PhotoShop riescono a fare quello che vuoi tu.


  5. #5
    Utente di HTML.it L'avatar di Veronica80
    Registrato dal
    May 2006
    Messaggi
    2,110
    ahaha gibraaaaaa sempre a puntigliare!

    Ti spiego meglio cosa voglio fare (perchè mi sa che non hai capito nulla :P).

    Io devo far si che l'immagine da me selezionata venga ridimensionata su una scala FISSA (in questo caso 500x376). Siccome se la ridimensionassi e basta me la deformerebbe (a meno che il rapporto width/height non fosse uguale) ho bisogno di ritagliarla (se necessario)!

    Ora...il codice che ho postato fa tutto (resize+crop) però l'output è osceno...
    E non parlo dello sgranamento che scaturisce da un ingrandimento (ovvio che se sono bitmap sgrana) ma parlo di un'immagine che diventa QUASI irriconoscibile :P

    Tieni conto che sto ridimensionando immagini da 1200x900px a 500x376px quindi dubito sgranino anzi essendo una riduzione in scala direi che non dovrebbero sgranare per nulla! :P

    Ribadisco comunque che non si tratta di "sgranamento" ma proprio di un immagine spixelata a livelli indegni! (oltre che con colori saturati ecc)...quindi credo che il tutto dipenda dall'interpolazione ecc ma nel codice è tutto settato

    Ora continuo a smanettarci sopra!!

  6. #6
    Utente di HTML.it L'avatar di U235
    Registrato dal
    Mar 2006
    Messaggi
    1,523


    Veronica, che niente niente vieni da asp?

    guardati questo modulo e vedi cosa sbagli, vedrai che sarà un ottimo esercizio...

    (fai tasto dx su progetto-> aggiungi-> nuovo elemento-> modulo)
    codice:
    Imports System.Drawing.Drawing2D
    Imports System.IO
    Imports System.Drawing.Imaging
    
    Module ImageExtender
        Sub New()
        End Sub
        <System.Runtime.CompilerServices.Extension()> _
        Public Function ResizeImage(Image As Image, Width As Integer, Height As Integer) As Image
            Dim widthImage As Integer = Image.Width
            Dim heightImage As Integer = Image.Height
            If widthImage > Width OrElse heightImage > Height Then
                Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX)
                Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX)
    
                Dim ratio As Single = 0
                If widthImage < heightImage Then
                    ratio = CSng(widthImage) / CSng(heightImage)
                    widthImage = Width
                    heightImage = Convert.ToInt32(Math.Round(CSng(widthImage) / ratio))
                Else
                    ratio = CSng(heightImage) / CSng(widthImage)
                    heightImage = Height
                    widthImage = Convert.ToInt32(Math.Round(CSng(heightImage) / ratio))
                End If
                Return Image.GetThumbnailImage(widthImage, heightImage, Nothing, IntPtr.Zero)
            End If
            Return Image
        End Function
    
        <System.Runtime.CompilerServices.Extension()> _
        Public Function CropImage(Image As Image, Width As Integer, Height As Integer, X As Integer, Y As Integer, Imageformat As ImageFormat, _
      PixelFormat As PixelFormat) As Image
            Dim result As Image
            Dim ms As MemoryStream = Nothing
            Try
                If Image.Height < Height Then
                    Height = Image.Height
                End If
    
                If Image.Width < Width Then
                    Width = Image.Width
                End If
                Dim ImageTemp As New Bitmap(Width, Height, PixelFormat)
                ImageTemp.SetResolution(72, 72)
                Dim graphic As Graphics = Graphics.FromImage(ImageTemp)
                graphic.SmoothingMode = SmoothingMode.AntiAlias
                graphic.InterpolationMode = InterpolationMode.HighQualityBicubic
                graphic.PixelOffsetMode = PixelOffsetMode.HighQuality
                graphic.DrawImage(Image, New Rectangle(0, 0, Width, Height), X, Y, Width, Height, _
                 GraphicsUnit.Pixel)
                ms = New MemoryStream()
                ImageTemp.Save(ms, Imageformat)
                Image.Dispose()
                ImageTemp.Dispose()
                graphic.Dispose()
                result = Image.FromStream(ms)
    
                Return result
            Catch er As Exception
                Throw New Exception(er.Message)
            End Try
        End Function
    
        <System.Runtime.CompilerServices.Extension()> _
        Public Function CropImage(Image As Image, Width As Integer, Height As Integer, X As Integer, Y As Integer) As Image
            Return Image.CropImage(Width, Height, X, Y, ImageFormat.Bmp, PixelFormat.Format24bppRgb)
        End Function
    
        <System.Runtime.CompilerServices.Extension()> _
        Public Function ResizeAndCropCenter(image As Image, width As Integer, height As Integer) As Image
            Dim result As Image = image.ResizeImage(width, height)
            Dim x As Integer = If(result.Width > result.Height, (result.Width - width) / 2, 0)
            Dim y As Integer = If(result.Width < result.Height, (result.Height - height) / 2, 0)
            Return result.CropImage(width, height, x, y)
        End Function
    End Module
    e si usa così :
    codice:
    Image.FromFile("C:\cartella\immagine.png").ResizeAndCropCenter(500, 376).Save("immagineRidimensionata.jpg")
    'che equivale a
    Dim immagineOriginale = Image.FromFile("C:\cartella\immagine.png")
            Dim NuovaImmagineRidimensionata = immagineOriginale.ResizeAndCropCenter(500, 376)
            NuovaImmagineRidimensionata.Save("immagineRidimensionata.jpg")

  7. #7
    Utente di HTML.it L'avatar di pietro09
    Registrato dal
    Jan 2002
    Messaggi
    10,116
    Ho provato il codice originale proposto da Veronica80, e ho provato a correggerlo, per quanto possibile.

    codice:
        Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            ridimensiona("prova.jpg", "c:\tmp", "c:\tmp\tmp", 600, 300)
        End Sub
    
        Private Sub ridimensiona(ByVal nomeImg As String, ByVal nomePath As String, ByVal destPath As String, ByVal wFinaleImg As Integer, ByVal hFinaleImg As Integer)
            Dim nomeCompletoImg As String = nomePath & "/" & nomeImg
            Dim IntXSize As Integer
            Dim IntYSize As Integer
            Dim IntHalfWidth As Integer
            Dim IntHalfHeight As Integer
            Dim X As Integer
            Dim Y As Integer
            Dim compressione As Long = 1
    
    
            'Variabili per l'anteprima
            Dim ObjBMP As System.Drawing.Image
            Dim ObjGraphics As System.Drawing.Image
    
            'prendiamo alcune informazioni importanti dall'immagine orginale
            ObjBMP = New Bitmap(nomeCompletoImg)
    
            'Misure dell'immagine
            Dim IntImgW As Integer = ObjBMP.Width
            Dim IntImgH As Integer = ObjBMP.Height
    
            'Nuove misure dell'immagine servono per mantenere le proporzioni, per il mio caso mi basta ridimensionare in base all'altezza
    
            Dim IntNewImgW As Integer
            Dim IntNewImgH As Integer
    
            IntNewImgH = hFinaleImg
            IntNewImgW = CInt((hFinaleImg / IntImgH) * IntImgW)
    
            'ObjGraphics = ObjBMP.GetThumbnailImage(IntNewImgW, IntNewImgH, Nothing, IntPtr.Zero) 
            ObjGraphics = New System.Drawing.Bitmap(ObjBMP, IntNewImgW, IntNewImgH)
    
    
    
    
            Dim myImageCodecInfo As System.Drawing.Imaging.ImageCodecInfo
            Dim myEncoder As System.Drawing.Imaging.Encoder
            Dim myEncoderParameter As System.Drawing.Imaging.EncoderParameter
            Dim myEncoderParameters As System.Drawing.Imaging.EncoderParameters
    
    
            Dim i As Integer
            Dim encoders As System.Drawing.Imaging.ImageCodecInfo() = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
    
            For i = 0 To (encoders.Length - 1)
                If (encoders(i).MimeType = "image/jpeg") Then
                    myImageCodecInfo = encoders(i)
                End If
            Next i
    
            myEncoder = System.Drawing.Imaging.Encoder.Quality
    
            myEncoderParameters = New System.Drawing.Imaging.EncoderParameters(1)
    
            myEncoderParameter = New System.Drawing.Imaging.EncoderParameter(myEncoder, compressione)
    
            myEncoderParameters.Param(0) = myEncoderParameter
    
            'ObjGraphics = ObjBMP.GetThumbnailImage(IntNewImgW, IntNewImgH, Nothing, IntPtr.Zero)
    
    
            'Qui viene fatto il crop, se non vi è necessario saltatelo
            Dim ObjSysDrawImg As New System.Drawing.Bitmap(wFinaleImg, hFinaleImg, PixelFormat.Format24bppRgb)
    
            Dim ObjGraphics2 As Graphics = Graphics.FromImage(ObjSysDrawImg)
    
            ObjGraphics2.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
            ObjGraphics2.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
            ObjGraphics2.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
    
            IntXSize = ObjGraphics.Width - 1
            IntYSize = ObjGraphics.Height - 1
    
            IntHalfWidth = CInt(IntXSize / 2)
            IntHalfHeight = CInt(IntYSize / 2)
            X = CInt(IntHalfWidth - (wFinaleImg / 2))
            Y = CInt(IntHalfHeight - (hFinaleImg / 2))
            ObjGraphics2.DrawImage(ObjGraphics, New Rectangle(0, 0, wFinaleImg, hFinaleImg), New Rectangle(X, Y, wFinaleImg, hFinaleImg), GraphicsUnit.Pixel)
            ObjGraphics.Dispose()
            '------------------------------------------------------
    
    
    
            If IO.Directory.Exists(destPath) = False Then
                IO.Directory.CreateDirectory(destPath)
            End If
            'ObjSysDrawImg.Save(destPath & "\" & nomeImg, myImageCodecInfo, myEncoderParameters)
            ObjSysDrawImg.Save(destPath & "\" & nomeImg)
    
    
            ObjBMP.Dispose()
            ObjGraphics2.Dispose()
            ObjSysDrawImg.Dispose()
        End Sub
    a me sembra che vada.

    ps. La nostra bella lingua non ha bisogno di termini orribili quali croppare.
    Pietro

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.