问:
Ghostly outline around image after resize
I'm working on a website that will sell hand made jewelry and I'm finishing the image editor, but it's not behaving quite right.

Basically, the user uploads an image which will be saved as a source and then it will be resized to fit the user's screen and saved as a temp. The user will then go to a screen that will allow them to crop the image and then save it to it's final versions.

All of that works fine, except, the final versions have 3 bugs. First is some black horizontal line on the very bottom of the image. Second is an outline of sorts that follows the edges. I thought it was because I was reducing the quality, but even at 100% it still shows up... And lastly, I've noticed that the cropped image is always a couple of pixels lower than what I'm specifying...

Anyway, I'm hoping someone whose got experience in editing images with C# can maybe take a look at the code and see where I might be going off the right path.

Oh, by the way, this in an ASP.NET MVC application.

Here's the code:

<s>

```<code>public class ImageProvider {
    private readonly ProductProvider ProductProvider = null;

    private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
    private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
        c => (c.MimeType == "image/jpeg"));

    private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");
    private readonly short[][] Dimensions = new short[3][] {
        new short[2] { 640, 480 },
        new short[2] { 240, 0 },
        new short[2] { 80, 60 }
    }

    public ImageProvider(ProductProvider ProductProvider) {
        this.ProductProvider = ProductProvider;

        HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
    }

    public void Crop(string FileName, Image Image, Crop Crop) {
        using (Bitmap Source = new Bitmap(Image)) {
            using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Target)) {
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;

                    Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                }

                Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
            }
        }
    }

    public void CropAndResize(Product Product, Crop Crop) {
        using (Image Source = Image.FromFile(String.Format("{0}/{1}.source", Path, Product.ProductId))) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                float Percent = ((float)Source.Width / (float)Temp.Width);

                short Width = (short)(Temp.Width * Percent);
                short Height = (short)(Temp.Height * Percent);

                Crop.Height = (short)(Crop.Height * Percent);
                Crop.Left = (short)(Crop.Left * Percent);
                Crop.Top = (short)(Crop.Top * Percent);
                Crop.Width = (short)(Crop.Width * Percent);

                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Source, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(this.Dimensions[0], String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[1], String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[2], String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                }
            }
        }

        this.Purge(Product);
    }

    public void QueueFor( Product Product, HttpPostedFileBase PostedFile) {
        using (Image Image = Image.FromStream(PostedFile.InputStream)) {
            this.Resize(new short[2] {
                1152,
                0
            }, String.Format("{0}/{1}.temp", Path, Product.ProductId), Image, HighQualityEncoder);
        }

        PostedFile.SaveAs(String.Format("{0}/{1}.source", Path, Product.ProductId));
    }

    private void Purge(Product Product) {
        string Source = String.Format("{0}/{1}.source", Path, Product.ProductId);
        string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

        if (File.Exists(Source)) {
            File.Delete(Source);
        }
        if (File.Exists(Temp)) {
            File.Delete(Temp);
        }

        foreach (Img Img in Product.Imgs) {
            string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

            if (File.Exists(Cropped)) {
                File.Delete(Cropped);
            }
        }
    }

    public void Resize( short[] Dimensions, string FileName, Image Image, EncoderParameters EncoderParameters) {
        if (Dimensions[1] == 0) {
            Dimensions[1] = (short)(Image.Height / ((float)Image.Width / (float)Dimensions[0]));
        }

        using (Bitmap Bitmap = new Bitmap(Dimensions[0], Dimensions[1])) {
            using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Graphics.SmoothingMode = SmoothingMode.HighQuality;
                Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                Graphics.CompositingQuality = CompositingQuality.HighQuality;

                Graphics.DrawImage(Image, 0, 0, Dimensions[0], Dimensions[1]);
            };

            Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
        }
    }
}
</code>```

Here's one of the images this produces:

</s>

UPDATE

So, I sat down and read through MSDN for like 2 hours after I posted, verified the code I had. As far as I can tell, I'm using the highest possible quality settings when performing the manipulation.

Either way, I ended up cleaning up and streamlining the code a bit. I contemplated the need for the source file and decided to remove it because it was requiring me to do additional work to figure out the cropping dimensions that are based on the temp file. So, it's gone.

Also, somewhere along the streamlining, the black line disappeared, so I can only assume that the aspect ratio issues should have been corrected as @StefanE stated.

Also, as @VinayC said, the re-sizer was generating a value of 479 for the height (which I still don't get how, but whatever...), but that seems to have been corrected when I switched to using the System.Drawing.Size and System.Drawing.Rectangle classes all the way through instead of using my own classes which essentially do the same thing.

So, here's the updated code. The remaining <s>two bugs</s> bug still stand, so I have a "ghosting" outline all the way around the image (see second attachment) which I can narrow down to the resizing because it shows up in the first re-size where no cropping has occurred. <s>And the second bug is that the cropped versions are always positioned lower on the y axis than what I pass in as the cropper. I'd estimate it's a good 5%-8% lower than what I tell it, so not sure about that one (the positions shouldn't be changing... unless I'm passing in a bad number from jQuery, gotta check on that...).</s>

(My second bug ended up me sending bad values to begin with, the cropping div was getting its relative position based on the master content div, not the image container div. All fixed now.)

```<code>using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace Website.Models.Providers {
    public class ImageProvider {
        private readonly ProductProvider ProductProvider = null;

        private readonly EncoderParameters DefaultQualityEncoder = new EncoderParameters();
        private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
        private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
            c =>
                (c.MimeType == "image/jpeg"));
        private readonly Size[] Sizes = new Size[3] {
            new Size(640, 0),
            new Size(240, 0),
            new Size(80, 0)
        };

        private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");

        public ImageProvider(
            ProductProvider ProductProvider) {
            this.ProductProvider = ProductProvider;

            this.DefaultQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
            this.HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
        }

        public void Crop(
            string FileName,
            Image Image,
            Crop Crop) {
            using (Bitmap Source = new Bitmap(Image)) {
                using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                    using (Graphics Graphics = Graphics.FromImage(Target)) {
                        Graphics.CompositingMode = CompositingMode.SourceCopy;
                        Graphics.CompositingQuality = CompositingQuality.HighQuality;
                        Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Graphics.SmoothingMode = SmoothingMode.HighQuality;

                        Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                    };

                    Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
                };
            };
        }

        public void CropAndResize(
            Product Product,
            Crop Crop) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Temp, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), this.Sizes[0], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), this.Sizes[1], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), this.Sizes[2], Cropped, HighQualityEncoder);
                };
            };

            this.Purge(Product);
        }

        public void QueueFor(
            Product Product,
            Size Size,
            HttpPostedFileBase PostedFile) {
            using (Image Image = Image.FromStream(PostedFile.InputStream)) {
                this.Resize(String.Format("{0}/{1}.temp", Path, Product.ProductId), Size, Image, HighQualityEncoder);
            };
        }

        private void Purge(
            Product Product) {
            string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

            if (File.Exists(Temp)) {
                File.Delete(Temp);
            };

            foreach (Img Img in Product.Imgs) {
                string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

                if (File.Exists(Cropped)) {
                    File.Delete(Cropped);
                };
            };
        }

        public void Resize(
            string FileName,
            Size Size,
            Image Image,
            EncoderParameters EncoderParameters) {
            if (Size.Height == 0) {
                Size.Height = (int)(Image.Height / ((float)Image.Width / (float)Size.Width));
            };

            using (Bitmap Bitmap = new Bitmap(Size.Width, Size.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                    Graphics.CompositingMode = CompositingMode.SourceCopy;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;

                    Graphics.DrawImage(Image, new Rectangle(0, 0, Size.Width, Size.Height));
                };

                Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
            };
        }
    }
}
</code>```

This image shows the "ghosting" outline pointed to by red arrows.

答: I guess is that in your input/calculations, you are probably providing larger source rectangle than actually exists - for example, source image size 640 x 480 but while scaling (DrawImage call), it is getting passed as 640 x 479. Other way is also possible that destination rectangle is smaller than target bitmap - but it appears unlikely by looking at your code. Best way to trouble shoot is to put break-point and inspect source image size and compare it will source rectangle size (crop parameter)</p>

Body:
I'm working on a website that will sell hand made jewelry and I'm finishing the image editor, but it's not behaving quite right.

Basically, the user uploads an image which will be saved as a source and then it will be resized to fit the user's screen and saved as a temp. The user will then go to a screen that will allow them to crop the image and then save it to it's final versions.

All of that works fine, except, the final versions have 3 bugs. First is some black horizontal line on the very bottom of the image. Second is an outline of sorts that follows the edges. I thought it was because I was reducing the quality, but even at 100% it still shows up... And lastly, I've noticed that the cropped image is always a couple of pixels lower than what I'm specifying...

Anyway, I'm hoping someone whose got experience in editing images with C# can maybe take a look at the code and see where I might be going off the right path.

Oh, by the way, this in an ASP.NET MVC application.

Here's the code:

<s>

public class ImageProvider {
    private readonly ProductProvider ProductProvider = null;

    private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
    private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
        c => (c.MimeType == "image/jpeg"));

    private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");
    private readonly short[][] Dimensions = new short[3][] {
        new short[2] { 640, 480 },
        new short[2] { 240, 0 },
        new short[2] { 80, 60 }
    }

    public ImageProvider(ProductProvider ProductProvider) {
        this.ProductProvider = ProductProvider;

        HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
    }

    public void Crop(string FileName, Image Image, Crop Crop) {
        using (Bitmap Source = new Bitmap(Image)) {
            using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Target)) {
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;

                    Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                }

                Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
            }
        }
    }

    public void CropAndResize(Product Product, Crop Crop) {
        using (Image Source = Image.FromFile(String.Format("{0}/{1}.source", Path, Product.ProductId))) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                float Percent = ((float)Source.Width / (float)Temp.Width);

                short Width = (short)(Temp.Width * Percent);
                short Height = (short)(Temp.Height * Percent);

                Crop.Height = (short)(Crop.Height * Percent);
                Crop.Left = (short)(Crop.Left * Percent);
                Crop.Top = (short)(Crop.Top * Percent);
                Crop.Width = (short)(Crop.Width * Percent);

                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Source, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(this.Dimensions[0], String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[1], String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[2], String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                }
            }
        }

        this.Purge(Product);
    }

    public void QueueFor( Product Product, HttpPostedFileBase PostedFile) {
        using (Image Image = Image.FromStream(PostedFile.InputStream)) {
            this.Resize(new short[2] {
                1152,
                0
            }, String.Format("{0}/{1}.temp", Path, Product.ProductId), Image, HighQualityEncoder);
        }

        PostedFile.SaveAs(String.Format("{0}/{1}.source", Path, Product.ProductId));
    }

    private void Purge(Product Product) {
        string Source = String.Format("{0}/{1}.source", Path, Product.ProductId);
        string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

        if (File.Exists(Source)) {
            File.Delete(Source);
        }
        if (File.Exists(Temp)) {
            File.Delete(Temp);
        }

        foreach (Img Img in Product.Imgs) {
            string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

            if (File.Exists(Cropped)) {
                File.Delete(Cropped);
            }
        }
    }

    public void Resize( short[] Dimensions, string FileName, Image Image, EncoderParameters EncoderParameters) {
        if (Dimensions[1] == 0) {
            Dimensions[1] = (short)(Image.Height / ((float)Image.Width / (float)Dimensions[0]));
        }

        using (Bitmap Bitmap = new Bitmap(Dimensions[0], Dimensions[1])) {
            using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Graphics.SmoothingMode = SmoothingMode.HighQuality;
                Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                Graphics.CompositingQuality = CompositingQuality.HighQuality;

                Graphics.DrawImage(Image, 0, 0, Dimensions[0], Dimensions[1]);
            };

            Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
        }
    }
}

Here's one of the images this produces:

</s>

UPDATE

So, I sat down and read through MSDN for like 2 hours after I posted, verified the code I had. As far as I can tell, I'm using the highest possible quality settings when performing the manipulation.

Either way, I ended up cleaning up and streamlining the code a bit. I contemplated the need for the source file and decided to remove it because it was requiring me to do additional work to figure out the cropping dimensions that are based on the temp file. So, it's gone.

Also, somewhere along the streamlining, the black line disappeared, so I can only assume that the aspect ratio issues should have been corrected as @StefanE stated.

Also, as @VinayC said, the re-sizer was generating a value of 479 for the height (which I still don't get how, but whatever...), but that seems to have been corrected when I switched to using the System.Drawing.Size and System.Drawing.Rectangle classes all the way through instead of using my own classes which essentially do the same thing.

So, here's the updated code. The remaining <s>two bugs</s> bug still stand, so I have a "ghosting" outline all the way around the image (see second attachment) which I can narrow down to the resizing because it shows up in the first re-size where no cropping has occurred. <s>And the second bug is that the cropped versions are always positioned lower on the y axis than what I pass in as the cropper. I'd estimate it's a good 5%-8% lower than what I tell it, so not sure about that one (the positions shouldn't be changing... unless I'm passing in a bad number from jQuery, gotta check on that...).</s>

(My second bug ended up me sending bad values to begin with, the cropping div was getting its relative position based on the master content div, not the image container div. All fixed now.)

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace Website.Models.Providers {
    public class ImageProvider {
        private readonly ProductProvider ProductProvider = null;

        private readonly EncoderParameters DefaultQualityEncoder = new EncoderParameters();
        private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
        private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
            c =>
                (c.MimeType == "image/jpeg"));
        private readonly Size[] Sizes = new Size[3] {
            new Size(640, 0),
            new Size(240, 0),
            new Size(80, 0)
        };

        private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");

        public ImageProvider(
            ProductProvider ProductProvider) {
            this.ProductProvider = ProductProvider;

            this.DefaultQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
            this.HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
        }

        public void Crop(
            string FileName,
            Image Image,
            Crop Crop) {
            using (Bitmap Source = new Bitmap(Image)) {
                using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                    using (Graphics Graphics = Graphics.FromImage(Target)) {
                        Graphics.CompositingMode = CompositingMode.SourceCopy;
                        Graphics.CompositingQuality = CompositingQuality.HighQuality;
                        Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Graphics.SmoothingMode = SmoothingMode.HighQuality;

                        Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                    };

                    Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
                };
            };
        }

        public void CropAndResize(
            Product Product,
            Crop Crop) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Temp, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), this.Sizes[0], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), this.Sizes[1], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), this.Sizes[2], Cropped, HighQualityEncoder);
                };
            };

            this.Purge(Product);
        }

        public void QueueFor(
            Product Product,
            Size Size,
            HttpPostedFileBase PostedFile) {
            using (Image Image = Image.FromStream(PostedFile.InputStream)) {
                this.Resize(String.Format("{0}/{1}.temp", Path, Product.ProductId), Size, Image, HighQualityEncoder);
            };
        }

        private void Purge(
            Product Product) {
            string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

            if (File.Exists(Temp)) {
                File.Delete(Temp);
            };

            foreach (Img Img in Product.Imgs) {
                string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

                if (File.Exists(Cropped)) {
                    File.Delete(Cropped);
                };
            };
        }

        public void Resize(
            string FileName,
            Size Size,
            Image Image,
            EncoderParameters EncoderParameters) {
            if (Size.Height == 0) {
                Size.Height = (int)(Image.Height / ((float)Image.Width / (float)Size.Width));
            };

            using (Bitmap Bitmap = new Bitmap(Size.Width, Size.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                    Graphics.CompositingMode = CompositingMode.SourceCopy;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;

                    Graphics.DrawImage(Image, new Rectangle(0, 0, Size.Width, Size.Height));
                };

                Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
            };
        }
    }
}

This image shows the "ghosting" outline pointed to by red arrows.


来源: stackexchange

问:
Heroku PostgreSQL - how does an SSL connection occur without certificates?
I have a Heroku PostgreSQL database. Using the credentials (host, database, username, password) supplied by Heroku, I can connect from my local machine using the PSequel client. Since Heroku requires SSL, I have to check off "Use SSL", which causes additional fields to appear (client key, client certificate, server root certificate). However, Heroku does not provide such certificates. I am able to connect to the database by checking off "Use SSL", but without providing those certificates to PSequel.

How does this work? I was under the impression that certificates are needed for an SSL connection. Without certificates, my understanding is that you could do key exchange and have encryption, but you don't know who you are talking to, so you are vulnerable to a man-in-the-middle attack. According to my understanding, I must not be connecting to my Heroku PostgreSQL database with SSL, or am I wrong?

In the past, I have used Google Cloud SQL (MySQL) and Sequel Pro. In that setup, I set my Cloud SQL settings to require SSL, and Google provided me with certificates (client key, client cert, and server CA) that I then supplied to Sequel Pro in order to connect using SSL. If I try to connect without supplying the certs (but checking off "Connect using SSL", and entering the correct host, username, password), I am not able to connect, and instead get "access denied".

答:
You should ask PSequel, as this is not open source, so I cannot look at the code.

Normally, when a PostgreSQL server is set up for SSL connections, the client can force SSL connections by using the connection option sslmode=require, and you don't need to have a client certificate for that (SSL is used for encryprion then, not for authentication).

ContentLicense: CC BY-SA 3.0


问:
Meteor method error - allowed by the schema [validation-error]
I'm getting the following error and have no idea why I'm pretty sure I'm doing everything correctly. I'm passing an array of objects and validating against that.

Method

```<code>export const insert = new ValidatedMethod({
    name: 'lineups.insert',

    // Validation
    validate(args) {
        console.log(args);
        new SimpleSchema({
            business: {  type: [Object] },
            competitors: { type: [Object] },
            location: { type: Object },
            type: { type: String }
        }).validate(args)
    },

    // Run
    run({ lineupsId}) {

        const loggedInUser = Meteor.user();

        // check user roles
        if (!loggedInUser) {
            throw new Meteor.Error(403, 'Access Denied');
        }
    }
});
</code>```

Here are the arg that the method gets

```<code>Object {business: Array[1], competitors: Array[1], location: Object, type: "Business Analysis"}
</code>```

But I'm getting the following error
business.0.placeID is not allowed by the schema [validation-error]

Calling the method

```<code>let businessArray = $.map(Session.get('business'), function(value, index) {
            return [{placeID:value.place_id, name:value.name}];
        });

insert.call({
            business:  businessArray,
            competitors:  Session.get('competitors'),
            location: Session.get('location'),
            type:Session.get('type')
        }, (err, res) => {
            if (err) {
                if (ValidationError.is(err)) {
                    toastr.error(err.message);
                }
            } else {
                toastr.error('Success, lineup have been created');
            }
        });
</code>```

答:
Try this, </p>

```<code>validate(args) {
    console.log(args);
    new SimpleSchema({
        business: {  blackbox: true, type: [Object] },
        competitors: { blackbox: true, type: [Object] },
        location: { blackbox: true, type: Object },
        type: { type: String }
    }).validate(args)
},
</code>```

Body:
I'm getting the following error and have no idea why I'm pretty sure I'm doing everything correctly. I'm passing an array of objects and validating against that.

Method

export const insert = new ValidatedMethod({
    name: 'lineups.insert',

    // Validation
    validate(args) {
        console.log(args);
        new SimpleSchema({
            business: {  type: [Object] },
            competitors: { type: [Object] },
            location: { type: Object },
            type: { type: String }
        }).validate(args)
    },

    // Run
    run({ lineupsId}) {

        const loggedInUser = Meteor.user();

        // check user roles
        if (!loggedInUser) {
            throw new Meteor.Error(403, 'Access Denied');
        }
    }
});

Here are the arg that the method gets

Object {business: Array[1], competitors: Array[1], location: Object, type: "Business Analysis"}

But I'm getting the following error
business.0.placeID is not allowed by the schema [validation-error]

Calling the method

let businessArray = $.map(Session.get('business'), function(value, index) {
            return [{placeID:value.place_id, name:value.name}];
        });

insert.call({
            business:  businessArray,
            competitors:  Session.get('competitors'),
            location: Session.get('location'),
            type:Session.get('type')
        }, (err, res) => {
            if (err) {
                if (ValidationError.is(err)) {
                    toastr.error(err.message);
                }
            } else {
                toastr.error('Success, lineup have been created');
            }
        });

Body:
Try this,

validate(args) {
    console.log(args);
    new SimpleSchema({
        business: {  blackbox: true, type: [Object] },
        competitors: { blackbox: true, type: [Object] },
        location: { blackbox: true, type: Object },
        type: { type: String }
    }).validate(args)
},


问:
sails js authentication middle wares
I am new in node js,  using sails.js as framework for developing application.Have using mysql as database. Need to know, is this possible to add middlewares for admin login check in routes?.</p>

答:
Sails out of the box supports all middleware which are supported by express.

You can very well in use passport (which though might be an overkill) with sails.

Title: sails js authentication middle wares


问:
Which data type should I use for declaring number equal to 12000000000 in JAVA(JDK1.7)?
After using class BigInteger my program on platform showed Memory Limit Exceeded. </p>

答: The maximal value a long can save (Long.MAX_VALUE) is 9,223,372,036,854,775,807. As you say you want to save a number equal to 12,000,000,000 it should be totally possible to save it using a long, because your number is still much smaller that Long.MAX_VALUE...

ContentLicense: CC BY-SA 4.0


问:
Reload Ajax Content from on.Change function after Page has been refreshed
I use a dropdown menu where the user can select specific subjects. If a subject is selected via dropdown, a textbox pops up via ajax and the user can enter stuff.

The problem is that if the form has been submitted and stuff in the form was missing or if the user simply refreshes the page, the ajax content (the text box) disappears and only shows up again, when another subject is selected.

This probably stems from my ajax script, which uses change and thus only puts the ajax-input into the div when the dropdown is changed again:

```<code>$(function() {
$('#subjectapp1').change(function()
{
var self = $(this);

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

});
});
</code>```

My dropdown menu:

```<code><select name="subject1" id="subjectapp1">
<option value="">Please choose</option>
<?php foreach ($subjects as $subject){ ?>
  <option <?php if ($_POST['subject1'] == $fach['subject_id']) {echo 'selected';} ?> value="<?php echo $subject['subject_id']; ?>"><?php echo $subject['subject']; ?></option>
</code>```

The div it is loaded into:

```<code><div id="subjectqualidiv1"></div>
</code>```

The ajax content (subjectpartial1.php) simply contains a text box in which the user can enter his qualification.

Is there a possibility that the ajax content is automatically loaded into the div when the page refreshes without the need to change the subjects again?

EDIT (WORKS): Based on the comments I tried the following, which yields the desired result:

```<code>$(document).ready(function () {
// For loading the ajax content on refresh/form submit
    var subject1 = $('#subjectapp1');

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: subject1.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

$('#subjectapp1').change(function()
{
var self = $(this);

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

});
});
</code>```

Thank you!

答: You can add your function that calls your AJAX to the $(document).ready() function which executes on page load. Be careful to check for valid data before executing your function because there may be instances when the page loads and the selector will be empty. For missing information you may want to look into the required attribute in HTML, which will prevent form submission if no data exists for that element. That will prevent a refresh for insufficient data.

Body:
I use a dropdown menu where the user can select specific subjects. If a subject is selected via dropdown, a textbox pops up via ajax and the user can enter stuff.

The problem is that if the form has been submitted and stuff in the form was missing or if the user simply refreshes the page, the ajax content (the text box) disappears and only shows up again, when another subject is selected.

This probably stems from my ajax script, which uses change and thus only puts the ajax-input into the div when the dropdown is changed again:

$(function() {
$('#subjectapp1').change(function()
{
var self = $(this);

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

});
});

My dropdown menu:

<select name="subject1" id="subjectapp1">
<option value="">Please choose</option>
<?php foreach ($subjects as $subject){ ?>
  <option <?php if ($_POST['subject1'] == $fach['subject_id']) {echo 'selected';} ?> value="<?php echo $subject['subject_id']; ?>"><?php echo $subject['subject']; ?></option>

The div it is loaded into:

The ajax content (subjectpartial1.php) simply contains a text box in which the user can enter his qualification.

Is there a possibility that the ajax content is automatically loaded into the div when the page refreshes without the need to change the subjects again?

EDIT (WORKS): Based on the comments I tried the following, which yields the desired result:

$(document).ready(function () {
// For loading the ajax content on refresh/form submit
    var subject1 = $('#subjectapp1');

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: subject1.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

$('#subjectapp1').change(function()
{
var self = $(this);

$.post("/blabla/potatoe/subjectpartial1.php",
{
subject1: self.val()
},
function(data)
{
    $('#subjectqualidiv1').html(data);
});

});
});

Thank you!


问:
How to save file with custom file extension in java?
Dear brothers Hope you all right?
I'm designing a document program, however, rather to save file .text extension or using any other MS-Office API in java, i want to create my custom file format such as ".sad" extension so that this sort of file can only be read by my programs, how this can be possible?</p>

答:
Your requirement seems ambiguous. Are you looking to make a program that creates MS Office Word documents or plain text files with a custom file extension?

In the case of the former, you can't have a custom extension as MS Word documents, by definition, have a .doc / .docx extension.

However, if you are looking to create a program that produces text files then you can easily have a custom extension. Just look at this tutorial: How to create a file in Java


问:
Installing pip using python 2.7 in cenOS 6
I am having CentOS 6 with below python:

Default:

```<code>[root@localhost vagrant]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code>```

Custom:

```<code>[root@localhost vagrant]# python2.7
Python 2.7.13 (default, Jul  7 2017, 12:01:53)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code>```

When I am trying to install pip using Python2.7 then getting below error:

```<code>[root@localhost vagrant]# python2.7 get-pip.py
Traceback (most recent call last):
  File "get-pip.py", line 20061, in <module>
    main()
  File "get-pip.py", line 194, in main
    bootstrap(tmpdir=tmpdir)
  File "get-pip.py", line 82, in bootstrap
    import pip
zipimport.ZipImportError: can't decompress data; zlib not available
</code>```

If the installation is done via yum(I suppose uses default python) then pip gets installed successfully but I am facing issues while installing any module via pip with Error: InsecurePlatformWarning
And suggests for python upgrade.
How can this be fixed and has some1 face similar kind of issue?

答:
As the error message says, you are missing a library. Run

```<code>yum install zlib-devel
</code>```

and the problem should be fixed. Note, you might need to run with sudo.

Body:
I am having CentOS 6 with below python:

Default:

[root@localhost vagrant]# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Custom:

[root@localhost vagrant]# python2.7
Python 2.7.13 (default, Jul  7 2017, 12:01:53)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

When I am trying to install pip using Python2.7 then getting below error:

[root@localhost vagrant]# python2.7 get-pip.py
Traceback (most recent call last):
  File "get-pip.py", line 20061, in <module>
    main()
  File "get-pip.py", line 194, in main
    bootstrap(tmpdir=tmpdir)
  File "get-pip.py", line 82, in bootstrap
    import pip
zipimport.ZipImportError: can't decompress data; zlib not available

If the installation is done via yum(I suppose uses default python) then pip gets installed successfully but I am facing issues while installing any module via pip with Error: InsecurePlatformWarning
And suggests for python upgrade.
How can this be fixed and has some1 face similar kind of issue?

Body:
As the error message says, you are missing a library. Run

yum install zlib-devel

and the problem should be fixed. Note, you might need to run with sudo.


问:
Paypal Buy Now button with variable/dynamic price
This is not a duplicate of this post.

I quote from the linked post:

As of June 29, 2017 I see this not working. Paypal has again changed its rules, and I don't think it any longer accepts hidden HTML fields in the form submission: they must be set in the button editor at Paypal.

Paypal documentation is a mess. Half of the links are broken and the other half of the links point to the documentation index.

Does any brain out there know how to achieve a Paypal Payment Button where I can set the price dynamically?

答:
PayPal recommended to use Express checkout client side integration and you can send the amount dynamically from your website to PayPal code.

Refer the following links for PayPal Express checkout client side integration:

https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/client-side-REST-integration/

https://developer.paypal.com/demo/checkout/#/pattern/client

Otheriwse, please try with the below PayPal HTML button code.

```<code><form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
  <!-- Identify your business so that you can collect the payments. -->
  <input type="hidden" name="business" value="Yourbusinessemail@paypal.com"> <!-- Add your PayPal Seller/Business email address Required-->
  <!-- Specify a Buy Now button. -->
  <input type="hidden" name="cmd" value="_xclick">
  <!-- Specify details about the item that buyers will purchase. -->
  <input type="hidden" name="item_name" value=""> <!-- Add Description e.g your room type Required-->
  <input type="hidden" name="amount" value=""> <!-- Dynamically add Total Amount Required-->
  <input type="hidden" name="currency_code" value=""> <!-- Update to your currency -->
  <input id="invoice" type="hidden" value="" name="invoice"> <!-- Add Unique invoice for each transaction -->
  <input type="hidden" name="notify_url" value="www.yourwebsite.com/ipn.php"> <!-- Please add IPN URL You can use this service to automate back-office and administrative functions, including fulfilling orders, tracking customers, and providing status and other information related to transactions. -->
  <input type='hidden' name='cancel_return' value='' /> <!-- Take customers to this URL when they cancel their checkout -->
  <input type='hidden' name='return' value='' /> <!-- Take customers to this URL when they finish their checkout  -->
  <!-- Display the payment button. -->
  <input type="image" name="submit" border="0" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="PayPal - The safer, easier way to pay online">
</form>

HTML Variables - https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/
Buy Now button - https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/buy_now_step_1/
IPN - https://developer.paypal.com/docs/classic/ipn/gs_IPN/
IPN - https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNSetup/
IPN Sample: https://github.com/paypal/ipn-code-samples
</code>```

Body:
PayPal recommended to use Express checkout client side integration and you can send the amount dynamically from your website to PayPal code.

Refer the following links for PayPal Express checkout client side integration:

https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/client-side-REST-integration/

https://developer.paypal.com/demo/checkout/#/pattern/client

Otheriwse, please try with the below PayPal HTML button code.

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
  <!-- Identify your business so that you can collect the payments. -->
  <input type="hidden" name="business" value="Yourbusinessemail@paypal.com"> <!-- Add your PayPal Seller/Business email address Required-->
  <!-- Specify a Buy Now button. -->
  <input type="hidden" name="cmd" value="_xclick">
  <!-- Specify details about the item that buyers will purchase. -->
  <input type="hidden" name="item_name" value=""> <!-- Add Description e.g your room type Required-->
  <input type="hidden" name="amount" value=""> <!-- Dynamically add Total Amount Required-->
  <input type="hidden" name="currency_code" value=""> <!-- Update to your currency -->
  <input id="invoice" type="hidden" value="" name="invoice"> <!-- Add Unique invoice for each transaction -->
  <input type="hidden" name="notify_url" value="www.yourwebsite.com/ipn.php"> <!-- Please add IPN URL You can use this service to automate back-office and administrative functions, including fulfilling orders, tracking customers, and providing status and other information related to transactions. -->
  <input type='hidden' name='cancel_return' value='' /> <!-- Take customers to this URL when they cancel their checkout -->
  <input type='hidden' name='return' value='' /> <!-- Take customers to this URL when they finish their checkout  -->
  <!-- Display the payment button. -->
  <input type="image" name="submit" border="0" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="PayPal - The safer, easier way to pay online">
</form>

HTML Variables - https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/
Buy Now button - https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/buy_now_step_1/
IPN - https://developer.paypal.com/docs/classic/ipn/gs_IPN/
IPN - https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNSetup/
IPN Sample: https://github.com/paypal/ipn-code-samples


问:
ElasticSearch : IN operator query with query_string
I want to match records against a query string, so I wrote the following query which is working fine:

```<code>{
  "query": {
    "query_string": {
      "fields": ["rollno","name"],
        "query": "*John*"
      }
  }
}
</code>```

Now, apart from matching the fields, I want to implement IN query against another field as well. I tried this query, as:

```<code>{
"query": {
    "query_string": {
        "fields": ["rollno", "name"],
        "query": "*John*"
    },
    "match": {
        "majorSubject": ["Biology", "Chemistry"]
    }
  }
}
</code>```

All I get is search_parse_exception.

How to this IN operation?

答:
You need to use a bool/must query in order to combine both sub-queries:

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fields": [
              "rollno",
              "name"
            ],
            "query": "*John*"
          }
        },
        {
          "terms": {
            "majorSubject": [
              "Biology",
              "Chemistry"
            ]
          }
        }
      ]
    }
  }
}
</code>```

if the majorSubject field is an analyzed string, use lowercase terms instead:

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fields": [
              "rollno",
              "name"
            ],
            "query": "*John*"
          }
        },
        {
          "terms": {
            "majorSubject": [
              "biology",
              "chemistry"
            ]
          }
        }
      ]
    }
  }
}
</code>```

Body:
I want to match records against a query string, so I wrote the following query which is working fine:

{
  "query": {
    "query_string": {
      "fields": ["rollno","name"],
        "query": "*John*"
      }
  }
}

Now, apart from matching the fields, I want to implement IN query against another field as well. I tried this query, as:

{
"query": {
    "query_string": {
        "fields": ["rollno", "name"],
        "query": "*John*"
    },
    "match": {
        "majorSubject": ["Biology", "Chemistry"]
    }
  }
}

All I get is search_parse_exception.

How to this IN operation?

Body:
You need to use a bool/must query in order to combine both sub-queries:

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fields": [
              "rollno",
              "name"
            ],
            "query": "*John*"
          }
        },
        {
          "terms": {
            "majorSubject": [
              "Biology",
              "Chemistry"
            ]
          }
        }
      ]
    }
  }
}

if the majorSubject field is an analyzed string, use lowercase terms instead:

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fields": [
              "rollno",
              "name"
            ],
            "query": "*John*"
          }
        },
        {
          "terms": {
            "majorSubject": [
              "biology",
              "chemistry"
            ]
          }
        }
      ]
    }
  }
}