How to capture file size of System.Drawing.Image?

1

I have a method to which I pass the parameter System.Drawing.Image and the percentage that that image will be after resize .

public static Image ResizeImagem(Image imgFoto, int percentual)
{
  float nPorcentagem = ((float)percentual / 100);

  int fonteLargura = imgFoto.Width;     //armazena a largura original da imagem origem
  int fonteAltura = imgFoto.Height;   //armazena a altura original da imagem origem
  int origemX = 0;        //eixo x da imagem origem
  int origemY = 0;        //eixo y da imagem origem

  int destX = 0;          //eixo x da imagem destino
  int destY = 0;          //eixo y da imagem destino
  //Calcula a altura e largura da imagem redimensionada
  int destWidth = (int)(fonteLargura * nPorcentagem);
  int destHeight = (int)(fonteAltura * nPorcentagem);

  //Cria um novo objeto bitmap
  Bitmap bmImagem = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
  //Define a resolu~ção do bitmap.
  bmImagem.SetResolution(imgFoto.HorizontalResolution, imgFoto.VerticalResolution);
  //Crima um objeto graphics e defina a qualidade
  Graphics grImagem = Graphics.FromImage(bmImagem);
  grImagem.InterpolationMode = InterpolationMode.HighQualityBicubic;

  //Desenha a imge usando o método DrawImage() da classe grafica
  grImagem.DrawImage(imgFoto,
      new Rectangle(destX, destY, destWidth, destHeight),
      new Rectangle(origemX, origemY, fonteLargura, fonteAltura),
      GraphicsUnit.Pixel);

  grImagem.Dispose();  //libera o objeto grafico
  return bmImagem;
}

But I need to get the size of this file in bytes so I run Resize until the image is 200KB.

    
asked by anonymous 19.11.2014 / 14:11

1 answer

3

So I understand what you need is to know the size of any file. It does not make any difference what's inside it. The result will be no different if you have a text, an image, a database structure, a song, or anything else.

For this you use the class FileInfo and get the Length . basically this is it:

long tamanho = new System.IO.FileInfo(path).Length; //path é o caminho completo do arquivo.

But if you need to get this information still in memory you can do something like this:

long tamanho;
using (var ms = new System.IO.MemoryStream()) {
    imgFoto.Save(ms, ImageFormat.Jpeg);
    tamanho = ms.Length;
}

I placed GitHub for future reference .

Choose the format you want to "save" the image. Choose from ImageFormat . Note that this is not saving to disk file. I can not guarantee that after the save to disk it's exactly the same size. There may be some slight variation, very small indeed.

    
19.11.2014 / 14:31