Would not save in S3 if i try the resize in the Put Method of the code

Sep 22, 2008 at 7:23 PM
Somehow its not saving correctly when resizing before sending to s3? Help!!!

 public HttpWebResponse CallService(HttpPostedFile file, string fileName)
        {
            DateTime timestamp = DateTime.Now;
            timestamp = new DateTime(timestamp.Year, timestamp.Month, timestamp.Day,
                                 timestamp.Hour, timestamp.Minute, timestamp.Second,
                                 timestamp.Millisecond, DateTimeKind.Local);

            string timestampString =
                timestamp.ToUniversalTime().ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z", System.Globalization.CultureInfo.InvariantCulture);

            string signiture = this.makeSignature(timestamp);

            string filePath = this.Path + fileName;

            string stringXml = String.Format(SR.SoapEnvelop,
                 ForXml(this.BucketName),
                 ForXml(filePath),
                 file.ContentLength,
                 this.GetAccessControlListXml(),
                 this.AccessKey,
                 timestamp.ToString("yyyy-MM-dd\\THH:mm:ss.fffzzz", System.Globalization.CultureInfo.InvariantCulture),
                 signiture);

            byte[] xml = Encoding.UTF8.GetBytes(stringXml);


            /***************************/
            int maxWidth = 450;
            int maxHeight = 450;

            int buffer = file.ContentLength;
            int nBytesRead = 0;
            Byte[] _FileByte = new Byte[buffer];
            Stream StreamImg = file.InputStream;
            nBytesRead = StreamImg.Read(_FileByte, 0, buffer);

            Encoding.ASCII.GetString(_FileByte, 0, nBytesRead);
            nBytesRead = StreamImg.Read(_FileByte, 0, buffer);

            file.InputStream.Read(_FileByte, 0, buffer);
            System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream);

            int imgWidth = img.Width;
            int imgHeight = img.Height;
            double percent2Shrink = -1;
            if (imgWidth >= imgHeight)
            {
                if (imgWidth > maxWidth)
                    percent2Shrink = (double)maxWidth / (double)imgWidth;
            }
            else
            {
                if (imgHeight > maxHeight)
                    percent2Shrink = (double)maxHeight / (double)imgHeight;
            }
            int newWidth = imgWidth;
            int newHeight = imgHeight;
            // Is resize required?
            if (percent2Shrink != -1)
            {
                newWidth = (int)(imgWidth * percent2Shrink);
                newHeight = (int)(imgHeight * percent2Shrink);
            }
            System.Drawing.Bitmap bmp = new Bitmap(img, newWidth, newHeight);

            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);
                g.DrawImage(img, 0, 0, newWidth, newHeight);
            }
            MemoryStream stream = new MemoryStream();
            ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
            EncoderParameters encoderParameters;
            encoderParameters = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
            bmp.GetThumbnailImage(newWidth, newHeight, null, System.IntPtr.Zero).Save(stream, info[1], encoderParameters);
            img.Dispose();
            bmp.Dispose();

            byte[] imgBinaryData = stream.ToArray();
            /**************************/


            DimeManager dm = new DimeManager(xml, convertByteArrayToStream(imgBinaryData));


            return dm.SendRequest();
        }
Coordinator
Sep 29, 2008 at 3:27 PM
When I find some time I will add OnStreamPreProcess event. I am sorry I won't have time to go through your code now.
Coordinator
Oct 11, 2008 at 4:44 AM

PreSendingFileStream event has been added. Please use it as:


protected void PreSendingFileStream(object sender, PreSendingFileStreamEventArgs args)
{
    Stream stream = args.FileStream;
    Stream changedStream;
   
    // modify stream here and set again the modified stream
   
    args.FileStream = changedStream;
}

<fjx:FileUploader ID="FileUploader1" runat="server" >
    <Adapters>
        <fjxau:AmazonUploader OnPreSendingFileStream="PreSendingFileStream"
            AccessKey="WebConfig:AmazonAccessKey"
            SecretKey="WebConfig:AmazonSecretKey"
            BucketName="media.flajaxian.com">
                <AccessControlList>
                    <fjxau:AccessControl URI="http://acs.amazonaws.com/groups/global/AllUsers" Permission="READ" />
                    <fjxau:AccessControl EmailAddress="john@flajaxian.com" Permission="FULL_CONTROL" />
                </AccessControlList>
        </fjxau:AmazonUploader>
    </Adapters>
</fjx:FileUploader>

Nov 9, 2008 at 6:19 PM
I know this thread is a bit old, but I was stuck on this same issue (only I WAS using the PreSendingFileStream event.

Eventually I figured out that you need to rewind the stream before you pass it back.  (Maybe the AmazonUploader should do this for us?)

like this:

void awsAdapter_PreSendingFileStream(object sender, com.flajaxian.PreSendingFileStreamEventArgs e)
        {
            //generate the thumbnail
            Stream stream = e.FileStream;
            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(stream);
            System.Drawing.Image smallImage = MyProject.Handlers.Pic.ScaleImageDownIfNecessary(originalImage, MAX_IMAGE_WIDTH_SMALL, MAX_IMAGE_HEIGHT_SMALL);
            Stream ms = new MemoryStream();
            smallImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            originalImage.Dispose();
            smallImage.Dispose();
            ms.Seek(0, SeekOrigin.Begin);
            e.FileStream = ms;
        }

ALSO!  You can reuse the amazonuploader.  For instance, I wanted to upload a full sized image and a thumbnailed image -- both to S3.

Like this:

*I added no adapters in the design time, just the fileuploader object -- then in my code behind:

in the page load:
fileUploader1.FileReceived += new EventHandler<com.flajaxian.FileReceivedEventArgs>(fileUploader1_FileReceived);

module level variables (to assure filename uniqueness):
        private Guid _newImageGUID = Guid.Empty;
        private string _newImageFileName = "";

private com.flajaxian.AWS.AmazonUploader getAWSAdapter(string bucketName)
        {
            com.flajaxian.AWS.AmazonUploader awsAdapter = new com.flajaxian.AWS.AmazonUploader();
            awsAdapter.AccessKey = ConfigurationManager.AppSettings["AmazonAccessKey"];
            awsAdapter.SecretKey = ConfigurationManager.AppSettings["AmazonSecretKey"];
            awsAdapter.BucketName = bucketName;
            com.flajaxian.AWS.AccessControl allUsers = new com.flajaxian.AWS.AccessControl();
            allUsers.URI = "http://acs.amazonaws.com/groups/global/AllUsers";
            allUsers.Permission = com.flajaxian.AWS.Permission.READ;
            com.flajaxian.AWS.AccessControl owner = new com.flajaxian.AWS.AccessControl();
            owner.EmailAddress = "me@gmail.com";
            owner.Permission = com.flajaxian.AWS.Permission.FULL_CONTROL;
            awsAdapter.AccessControlList.Add(allUsers);
            awsAdapter.AccessControlList.Add(owner);
            return awsAdapter;
        }

        void fileUploader1_FileReceived(object sender, com.flajaxian.FileReceivedEventArgs e)
        {
            com.flajaxian.AWS.AmazonUploader awsAdapter = getAWSAdapter("my.main.image.bucket.name");
            
            _newImageGUID = Guid.NewGuid();
            awsAdapter.FileNameDetermening += new EventHandler<com.flajaxian.FileNameDetermeningEventArgs>(awsAdapter_FileNameDetermening);
            awsAdapter.ProcessFile(e.File);

            //reuse the adapter to post the thumbnail
            //note that the file will have the same name in both buckets.
            awsAdapter.BucketName = "my.thumbnail.image.bucket.name";
            awsAdapter.PreSendingFileStream += new EventHandler<com.flajaxian.PreSendingFileStreamEventArgs>(awsAdapter_PreSendingFileStream);
            awsAdapter.ProcessFile(e.File);

        }

        void awsAdapter_FileNameDetermening(object sender, com.flajaxian.FileNameDetermeningEventArgs e)
        {
            _newImageFileName = _newImageGUID.ToString().Replace("-", "") + "_" + e.FileName;
            e.FileName = _newImageFileName;
        }



Coordinator
Nov 10, 2008 at 3:03 AM
Thanks for the code samples Chadkouse