views:

559

answers:

2

I got this block of code from link text and modified it a little because I want to use it with my AJAX Uploader that needs a Stream to be used for adding uploaded items into the attachments display;

public Stream ResizeFromStream(int MaxSideSize, Stream Buffer)
{
    int intNewWidth;
    int intNewHeight;
    System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer);

    // GET IMAGE FORMAT
    ImageFormat fmtImageFormat = imgInput.RawFormat;

    // GET ORIGINAL WIDTH AND HEIGHT
    int intOldWidth = imgInput.Width;
    int intOldHeight = imgInput.Height;

    // IS LANDSCAPE OR PORTRAIT ?? 
    int intMaxSide;

    if (intOldWidth >= intOldHeight)
    {
        intMaxSide = intOldWidth;
    }
    else
    {
        intMaxSide = intOldHeight;
    }


    if (intMaxSide > MaxSideSize)
    {
        // SET NEW WIDTH AND HEIGHT
        double dblCoef = MaxSideSize / (double)intMaxSide;
        intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
        intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
    }
    else
    {
        intNewWidth = intOldWidth;
        intNewHeight = intOldHeight;
    }

    // CREATE NEW BITMAP
    Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);

    // SAVE BITMAP TO STREAM
    MemoryStream imgStream = new MemoryStream();
    bmpResized.Save(imgStream, imgInput.RawFormat);

    // RELEASE RESOURCES
    imgInput.Dispose();
    bmpResized.Dispose();
    Buffer.Close();

    return imgStream;
}

and being called in this block of code;

private void ItemPicture_FileUploaded(object sender, UploaderEventArgs args)
{
    if (GetVisibleItemCount() >= 5)
        return;

    using (System.IO.Stream stream = args.OpenStream())
    {
        ImageResize ir = new ImageResize();
        // This returns a 0 byte stream
        ItemPictureAttachments.Upload(args.FileSize, args.FileName, ir.ResizeFromStream(640, stream));
        // This works fine
        // ItemPictureAttachments.Items.Add(args.FileSize, args.FileName, stream);
    }
}

Am I doing it wrong in returning the stream back to where it is being called from? Thanks!

A: 

Based on your code everything looks OK. I suggest you to put a break point at

Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);

and inspect whether imgInput is not empty. Or Perhaps there is something wrong with the ImageRawFormat.

Genady Sergeev
A: 

I tested your ResizeFromStream method using the PostedFile.Inputstream property of a regular ASP.NET File control, and that worked fine. Perhaps the problem is with the component you are using to retrieve the file's stream (args.OpenStream())?

Ravish
Yeah I'll just use the regular upload. Thanks guys! :)