Пример #1
0
        public static String SubirImagen(FileUpload subirImagen, int id)
        {
            //comprueba si hay archivo
            if (subirImagen.HasFile)
            {
                //comprueba si es una imagen
                if (subirImagen.PostedFile.ContentType == "image/jpeg" || subirImagen.PostedFile.ContentType == "image/gif" || subirImagen.PostedFile.ContentType == "image/png")
                {
                    //comprueba si pesa menos de 15mB.
                    if (subirImagen.PostedFile.ContentLength < 15985760)
                    {
                        //crea el nombre de la imagen con la fecha del momento + el id + la extension.
                        DateTime fecha        = DateTime.Now;
                        string   ext          = Path.GetExtension(subirImagen.FileName);
                        string   nombreImagen = id + "_" + fecha.Day.ToString() + fecha.Month.ToString() + fecha.Year.ToString() + "_" + fecha.Hour.ToString() + fecha.Minute.ToString() + fecha.Second.ToString() + fecha.Millisecond.ToString() + ext;

                        //comprueba si existe el directorio en el servidor, sino lo crea.
                        if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(@"IMAGENES_SUBIDAS\" + id)))
                        {
                            ;
                        }
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(@"IMAGENES_SUBIDAS\" + id));
                        }

                        //guardamos la ruta de la carpeta de imagenes del usuario.
                        string carpeta = System.Web.HttpContext.Current.Server.MapPath(@"IMAGENES_SUBIDAS\" + id + "\\");

                        //creamos un bitmap con la imagen subida.
                        Bitmap BMPoriginal = new Bitmap(subirImagen.FileContent);

                        //variables para redimensionar la imagen.
                        int    newHeight = 0, newWidth = 0;
                        Bitmap BMP;

                        //si es una imagen horizontal:
                        //si la imagen es mas ancha que 1600 calcula la proporcion de la imagen y
                        //la nueva altura, y la guarda en el bitmap definitivo con las medidas
                        //establecidas para que sea maximo 1600 de ancho, si es menos
                        //ancha que 1600 la guardamos tal cual.
                        if (BMPoriginal.Width >= BMPoriginal.Height)
                        {
                            if (BMPoriginal.Width > 1600)
                            {
                                decimal origWidth  = BMPoriginal.Width;
                                decimal origHeight = BMPoriginal.Height;
                                decimal imgRatio   = origHeight / origWidth;
                                newWidth = 1600; //ANCHO PREDEFINIDO
                                decimal newHeight_temp = newWidth * imgRatio;
                                newHeight = Convert.ToInt16(newHeight_temp);

                                BMP = new Bitmap(BMPoriginal, newWidth, newHeight);
                            }
                            else
                            {
                                BMP = BMPoriginal;
                            }
                        }
                        //else si es una imagen vertical:
                        //si la imagen es mas alta que 1600 calcula la proporcion de la imagen y
                        //el nuevo ancho, y la guarda en el bitmap definitivo con las medidas
                        //establecidas para que sea maximo 1600 de alto, si es menos
                        //alta que 1600 la guardamos tal cual.
                        else
                        {
                            if (BMPoriginal.Height > 1600)
                            {
                                decimal origWidth  = BMPoriginal.Width;
                                decimal origHeight = BMPoriginal.Height;
                                decimal imgRatio   = origWidth / origHeight;
                                newHeight = 1600; //Alto PREDEFINIDO
                                decimal newWidth_temp = newHeight * imgRatio;
                                newWidth = Convert.ToInt16(newWidth_temp);

                                BMP = new Bitmap(BMPoriginal, newWidth, newHeight);
                            }
                            else
                            {
                                BMP = BMPoriginal;
                            }
                        }

                        //convertimos el bitmap en un grafico y le aplicamos unos retoques de calidad.
                        Graphics Grafico = Graphics.FromImage(BMP);
                        Grafico.SmoothingMode     = SmoothingMode.AntiAlias;
                        Grafico.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Grafico.DrawImage(BMPoriginal, 0, 0, newWidth, newHeight);

                        //probamos de guardar la imagen en el servidor, y capturamos excepcion.
                        try
                        {
                            BMP.Save(carpeta + nombreImagen);
                        }
                        catch (ExternalException ex)
                        {
                            return(ex.InnerException.Message);
                        }

                        //vaciamos los objetos usados.
                        BMPoriginal.Dispose();
                        BMP.Dispose();
                        Grafico.Dispose();

                        //retornamos la ruta exacta de la imagen para poder guardala en la base de datos.
                        return("IMAGENES_SUBIDAS\\" + id + "\\" + nombreImagen);
                    }
                    //distintos mensajes de error de los ifs del principio de la funcion.
                    else
                    {
                        return("ERROR: Tamaño maximo 15MB.");
                    }
                }
                else
                {
                    return("ERROR: El archivo seleccionado no es una imagen.");
                }
            }
            else
            {
                return("ERROR: Selecciona una imagen porfavor");
            }
        }
Пример #2
0
        // Convert a bitmap to a memory mapped file
        // (Same as ConvertBitmapToMMF but uses CopyMemory to avoid using a byte array)
        private static IntPtr ConvertBitmapToMMF2(Bitmap BMPIn, bool DiscardBitmap, bool ConvertTo1Bit)
        {
            Bitmap           BMP;
            BITMAPINFOHEADER BIH;
            BitmapData       BMPData;
            int      ImageSize;
            int      MMFsize;
            int      PalEntries;
            RGBQUAD  rgb;
            GCHandle rgbGC;
            int      Offset;
            IntPtr   MMFhandle = IntPtr.Zero;
            IntPtr   MMFview   = IntPtr.Zero;
            IntPtr   RetPtr    = IntPtr.Zero;

            if (DiscardBitmap) // can destroy input bitmap
            {
                if (ConvertTo1Bit)
                {
                    BMP = BMPIn.Clone(new Rectangle(new Point(), BMPIn.Size), PixelFormat.Format1bppIndexed);
                    BMPIn.Dispose();
                    BMPIn = null;
                }
                else
                {
                    BMP = BMPIn;
                }
            }
            else                          // must keep input bitmap unchanged
            {
                if (ConvertTo1Bit)
                {
                    BMP = BMPIn.Clone(new Rectangle(new Point(), BMPIn.Size), PixelFormat.Format1bppIndexed);
                }
                else
                {
                    BMP = BMPIn.Clone(new Rectangle(new Point(), BMPIn.Size), BMPIn.PixelFormat);
                }
            }

            // Flip the bitmap (GDI+ bitmap scan lines are top down, GDI are bottom up)
            BMP.RotateFlip(RotateFlipType.RotateNoneFlipY);

            BMPData   = BMP.LockBits(new Rectangle(new Point(), BMP.Size), ImageLockMode.ReadOnly, BMP.PixelFormat);
            ImageSize = BMPData.Stride * BMP.Height;

            PalEntries = BMP.Palette.Entries.Length;

            BIH.biWidth         = BMP.Width;
            BIH.biHeight        = BMP.Height;
            BIH.biPlanes        = 1;
            BIH.biClrImportant  = 0;
            BIH.biCompression   = BI_RGB;
            BIH.biSizeImage     = (uint)ImageSize;
            BIH.biXPelsPerMeter = System.Convert.ToInt32(BMP.HorizontalResolution * 100 / 2.54);
            BIH.biYPelsPerMeter = System.Convert.ToInt32(BMP.VerticalResolution * 100 / 2.54);
            BIH.biBitCount      = 0; // to avoid "Use of unassigned local variable 'BIH'"
            BIH.biSize          = 0; // to avoid "Use of unassigned local variable 'BIH'"
            BIH.biClrImportant  = 0; // to avoid "Use of unassigned local variable 'BIH'"

            // Most of these formats are untested and the alpha channel is ignored
            switch (BMP.PixelFormat)
            {
            case PixelFormat.Format1bppIndexed:
                BIH.biBitCount = 1;
                break;

            case PixelFormat.Format4bppIndexed:
                BIH.biBitCount = 4;
                break;

            case PixelFormat.Format8bppIndexed:
                BIH.biBitCount = 8;
                break;

            case PixelFormat.Format16bppArgb1555:
            case PixelFormat.Format16bppGrayScale:
            case PixelFormat.Format16bppRgb555:
            case PixelFormat.Format16bppRgb565:
                BIH.biBitCount = 16;
                PalEntries     = 0;
                break;

            case PixelFormat.Format24bppRgb:
                BIH.biBitCount = 24;
                PalEntries     = 0;
                break;

            case PixelFormat.Format32bppArgb:
            case PixelFormat.Format32bppPArgb:
            case PixelFormat.Format32bppRgb:
                BIH.biBitCount = 32;
                PalEntries     = 0;
                break;
            }
            BIH.biClrUsed = (uint)PalEntries;
            BIH.biSize    = (uint)Marshal.SizeOf(BIH);

            MMFsize = Marshal.SizeOf(BIH) + PalEntries * Marshal.SizeOf(typeof(RGBQUAD)) + ImageSize;

            MMFhandle = CreateFileMappingMy(0xFFFFFFFF, 0, PAGE_READWRITE, 0, (uint)MMFsize, 0);
            if (!(MMFhandle.Equals(IntPtr.Zero)))
            {
                MMFview = MapViewOfFileMy(MMFhandle, FILE_MAP_WRITE, 0, 0, 0);
                if (MMFview.Equals(IntPtr.Zero))
                {
                    CloseHandle(MMFhandle);
                }
                else
                {
                    Marshal.StructureToPtr(BIH, MMFview, true);
                    Offset          = MMFview.ToInt32() + Marshal.SizeOf(BIH);
                    rgb.rgbReserved = 0;
                    for (int PalEntry = 0; PalEntry <= PalEntries - 1; PalEntry++)
                    {
                        rgb.rgbRed   = BMP.Palette.Entries[PalEntry].R;
                        rgb.rgbGreen = BMP.Palette.Entries[PalEntry].G;
                        rgb.rgbBlue  = BMP.Palette.Entries[PalEntry].B;

                        rgbGC = GCHandle.Alloc(rgb, GCHandleType.Pinned);
                        CopyMemory((uint)Offset, rgbGC.AddrOfPinnedObject(), (uint)Marshal.SizeOf(rgb));
                        rgbGC.Free();
                        Offset = Offset + Marshal.SizeOf(rgb);
                    }
                    CopyMemory((uint)Offset, BMPData.Scan0, (uint)ImageSize);
                    UnmapViewOfFileMy(MMFview);
                    RetPtr = MMFhandle;
                }
            }
            BMP.UnlockBits(BMPData);
            BMPData = null;
            BMP.Dispose();
            BMP = null;

            if (RetPtr.Equals(IntPtr.Zero))
            {
                MessageBox.Show("Failed to convert bitmap", "ConvertBitmapToMMF2", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            return(RetPtr);
        }
Пример #3
0
 /// <summary>
 /// Disposes of the texture bitmap
 /// </summary>
 public virtual void Dispose()
 {
     BMP.Dispose();
 }