Exemple #1
0
        /// <summary> </summary>
        public static bool smushit(int id, string image_name, String mimeType)
        {
            // sent file to yahoo
            string url = "http://www.smushit.com/ysmush.it/ws.php?";    // "http://www.smushit.com/ysmush.it/ws.php?";

            log.Info("trying smushit" + image_name);
            //reset the .ext file name
            posting image = ActiveRecordBase <posting> .Find(id);

            string orgFile = image_name;

            image_name = Regex.Replace(image_name, ".ext", "." + image.get_meta("ext"), RegexOptions.IgnoreCase);

            File.Copy(orgFile, image_name, true);

            NameValueCollection nvc = new NameValueCollection();
            //nvc.Add("id", "TTR");
            //nvc.Add("btn-submit-photo", "Upload");
            string yurl = "";

            try {
                String  responseData = httpService.HttpUploadFile(url, image_name, "files", file_mime.mime_type(image.get_meta("ext")), nvc);
                JObject obj          = JObject.Parse(responseData);
                yurl = (string)obj["dest"];     // what is the path?
            } catch {
            }
            if (!String.IsNullOrEmpty(yurl))
            {
                log.Info("did smushit" + yurl);
                byte[] imagebytes = httpService.DownloadBinary(yurl);
                file_handler.ByteArrayToFile(image_name, imagebytes);
                File.Copy(image_name, orgFile, true);    // overwirte the .ext with the new file.
                //File.Delete(image_name);
                deleteTmpIamges(image_name);
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public void Download(int id, int eventsid, int w, int h, int p, string m, bool protect, string pre, string mark, int maxage, bool nocache, bool mug)
        {
            CancelLayout();
            CancelView();
            log.Info("Starting download for image id " + id);
            posting image = ActiveRecordBase <posting> .Find(id);

            string uploadPath = "";

            if (image.static_file != null)
            {
                uploadPath = image.static_file;
                String fullpath = id + ".ext";
                uploadPath = Regex.Replace(uploadPath, "(.*)(\\\\.*?)(.*)", "$1");
                if (!uploadPath.EndsWith("\\"))
                {
                    uploadPath += "\\";
                }
            }
            else
            {
                // build the path for the new image
                uploadPath = Context.ApplicationPath + @"\uploads\";
                if (mug)
                {
                    uploadPath += @"mugshots\";
                }

                if (eventsid != 0)
                {
                    posting events = ActiveRecordBase <posting> .Find(eventsid);

                    uploadPath += @"events\" + events.id + @"\";

                    //check for events level image existence
                    string orgFile = HttpContext.Server.MapPath(uploadPath + id + ".ext");
                    if (!File.Exists(orgFile))
                    {
                        //it didn't so lets take a look at the pool for the image
                        string newuploadPath = Context.ApplicationPath + @"\uploads\";
                        string neworgFile    = HttpContext.Server.MapPath(newuploadPath + id + ".ext");
                        if (File.Exists(neworgFile))
                        {
                            uploadPath = Context.ApplicationPath + @"\uploads\";
                        }
                    }
                }
            }
            if (String.IsNullOrWhiteSpace(m))
            {
                m = "constrain";
                w = 1000;//this will be site prefenece for max served iamges.
                h = 1000;
            }

            string arg = (!String.IsNullOrEmpty(pre) ? "_" + pre + "_" : "");

            arg += (w != 0 ? "w_" + w + "_" : "");
            arg += (h != 0 ? "h_" + h + "_" : "");
            arg += (p != 0 ? "p_" + p + "_" : "");
            arg += (protect != false ? "pro_true_" : "");
            arg += (!String.IsNullOrEmpty(m) ? "m_" + m + "_" : "");
            arg += (!String.IsNullOrEmpty(mark) ? "mark_" + mark + "_" : "");


            string newFile = HttpContext.Server.MapPath(uploadPath + id + arg + ".ext");

            // if the process image doesn't Exist yet create it
            if (!File.Exists(newFile))
            {
                string baseFile = uploadPath + id + ".ext";
                if (!File.Exists(baseFile))
                {
                    baseFile = uploadPath + image.static_file;
                }

                System.Drawing.Image processed_image = System.Drawing.Image.FromFile(HttpContext.Server.MapPath(baseFile));
                //set some defaults
                image_handler.imageMethod methodChoice = image_handler.imageMethod.Percent;
                image_handler.Dimensions  dimensional  = image_handler.Dimensions.Width;

                //choose medth of sizing and set their defaults
                switch (m)
                {
                case "percent":
                    methodChoice = image_handler.imageMethod.Percent;
                    break;

                case "constrain":
                    methodChoice = image_handler.imageMethod.Constrain;
                    dimensional  = w != 0 ? image_handler.Dimensions.Width : image_handler.Dimensions.Height;
                    break;

                case "fixed":
                    methodChoice = image_handler.imageMethod.Fixed;
                    break;

                case "crop":
                    methodChoice = image_handler.imageMethod.Crop;
                    break;
                }
                new image_handler().process(id, processed_image, newFile, methodChoice, p, h, w, dimensional, protect, mark, image.get_meta("ext"));
            }

            // Read in the file into a byte array
            byte[] contents = null;
            try {
                contents = File.ReadAllBytes(HttpContext.Server.MapPath(uploadPath + id + arg + ".ext"));
            } catch (Exception ex) {
                log.Error("Error uploading file", ex);
            }

            HttpContext.Response.ClearContent();
            HttpContext.Response.ClearHeaders();
            if (contents != null)
            {
                String contentDisposition = "inline; filename=\"" + image.get_meta("filename") + arg + "." + image.get_meta("ext") + "\"";

                HttpContext.Response.Clear();
                String contentType = "applicaton/image";
                switch (image.get_meta("ext").ToLower())
                {
                case "gif":
                    contentType = "image/gif";
                    break;

                case "png":
                    contentType = "image/png";
                    break;

                case "jpg":
                case "jpe":
                case "jpeg":
                    contentType = "image/jpeg";
                    break;

                case "bmp":
                    contentType = "image/bmp";
                    break;

                case "tif":
                case "tiff":
                    contentType = "image/tiff";
                    break;

                case "eps":
                    contentType = "application/postscript";
                    break;

                default:
                    contentDisposition = "attachment; filename=\"" + image.get_meta("filename") + arg + "." + image.get_meta("ext") + "\"";
                    contentType        = "application/" + image.get_meta("ext").ToLower();
                    break;
                }

                // Setup the response
                HttpContext.Response.Buffer = true;
                HttpContext.Response.AddHeader("Content-Length", contents.Length.ToString());
                DateTime dt = DateTime.Now.AddYears(1);
                HttpContext.Response.Cache.SetExpires(dt);
                HttpContext.Response.Cache.SetMaxAge(new TimeSpan(dt.ToFileTime()));
                HttpContext.Response.Cache.SetValidUntilExpires(true);
                HttpContext.Response.Cache.SetCacheability(HttpCacheability.Public);
                HttpContext.Response.Expires     = 0;
                HttpContext.Response.ContentType = contentType;
                //HttpContext.Response.AddHeader("Content-Disposition", "inline; filename=\"" + image.FileName + arg + "." + image.Ext + "\"");
                HttpContext.Response.Cache.SetMaxAge(new TimeSpan(84, 0, 0, 0, 0));
                // Write the file to the response
                HttpContext.Response.BinaryWrite(contents);
            }
            log.Info("Finished download for image id " + id + ", length: " + contents.Length.ToString() + " bytes");
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        /// <summary> </summary>
        public void UpdatePool([ARDataBind("image", Validate = true, AutoLoad = AutoLoadBehavior.NewRootInstanceIfInvalidKey)] posting image, HttpPostedFile newimage)
        {
            ActiveRecordMediator <posting> .Save(image);

            if (newimage.ContentLength != 0)
            {
                String   Fname     = System.IO.Path.GetFileName(newimage.FileName);
                String[] fileparts = Fname.Split('.');
                if (String.IsNullOrEmpty(image.get_meta("file_name")))
                {
                    image.meta_data.Add(new meta_data()
                    {
                        meta_key = "file_name", value = fileparts[0]
                    });
                }
                image.meta_data.Add(new meta_data()
                {
                    meta_key = "ext", value = fileparts[1]
                });

                // Make a copy of the stream to stop the destrustion of the gif animation per
                // http://stackoverflow.com/questions/8763630/c-sharp-gif-image-to-memorystream-and-back-lose-animation
                Stream       stream       = newimage.InputStream;
                MemoryStream memoryStream = new MemoryStream();
                httpService.CopyStream(stream, memoryStream);
                memoryStream.Position = 0;
                stream = memoryStream;

                //set up the image up from the stream
                //System.Drawing.Image processed_image = System.Drawing.Image.FromStream(newimage.InputStream);

                System.Drawing.Image processed_image = null;

                if (image.get_meta("ext") == "gif")
                {
                    //set up the image up from the stream
                    processed_image = System.Drawing.Image.FromStream(stream);//newimage.InputStream);
                }
                else
                {
                    processed_image = System.Drawing.Image.FromStream(newimage.InputStream);

                    if (image_handler.isFileACMYKJpeg(processed_image) || image_handler.isByteACMYK(stream))
                    {
                        Flash["error"] = "You have uploaded a CMYK image.  Please conver to RGB first.";
                        RedirectToReferrer();
                        return;
                    }
                }



                // a var for uploads will start here
                String uploadPath = file_info.root_path() + @"\uploads\";

                if (!file_info.dir_exists(uploadPath))
                {
                    System.IO.Directory.CreateDirectory(uploadPath);
                }
                string newFile = uploadPath + image.id + ".ext";
                new image_handler().process(image.id, processed_image, newFile, image_handler.imageMethod.Constrain, 0, 0, 1000, image_handler.Dimensions.Width, true, "", image.get_meta("ext"));
            }
            ActiveRecordMediator <posting> .Save(image);

            RedirectToAction("list");
        }
        /// <summary> </summary>
        public void Update(
            [ARDataBind("image", Validate = true, AutoLoad = AutoLoadBehavior.NewRootInstanceIfInvalidKey)] posting image,
            HttpPostedFile newimage,
            int events_id,
            bool ajax
            )
        {
            ActiveRecordMediator <posting> .Save(image);

            if (newimage.ContentLength != 0)
            {
                String   Fname     = System.IO.Path.GetFileName(newimage.FileName);
                String[] fileparts = Fname.Split('.');
                if (String.IsNullOrEmpty(image.get_meta("file_name")))
                {
                    image.meta_data.Add(new meta_data()
                    {
                        meta_key = "file_name", value = fileparts[0]
                    });
                }
                image.meta_data.Add(new meta_data()
                {
                    meta_key = "ext", value = fileparts[1]
                });


                Stream       stream       = newimage.InputStream;
                MemoryStream memoryStream = new MemoryStream();
                httpService.CopyStream(stream, memoryStream);
                memoryStream.Position = 0;
                stream = memoryStream;


                //set up the image up from the stream
                System.Drawing.Image processed_image = System.Drawing.Image.FromStream(newimage.InputStream);

                if (image_handler.isFileACMYKJpeg(processed_image) || image_handler.isByteACMYK(stream))
                {
                    if (ajax)
                    {
                        CancelView();
                        CancelLayout();
                        RenderText("You have uploaded a CMYK image.  Please conver to RGB first.");
                        return;
                    }
                    Flash["error"] = "You have uploaded a CMYK image.  Please conver to RGB first.";
                    RedirectToReferrer();
                    return;
                }


                // a var for uploads will start here
                String uploadPath = file_info.root_path();
                if (!uploadPath.EndsWith("\\"))
                {
                    uploadPath += "\\";
                }
                uploadPath += @"uploads\";

                if (events_id != 0)
                {
                    uploadPath += @"events\" + events_id + @"\";
                }
                if (!file_info.dir_exists(uploadPath))
                {
                    System.IO.Directory.CreateDirectory(uploadPath);
                }
                string newFile = uploadPath + image.id + ".ext";
                log.Info("uploadfilename: " + newFile);
                //stellar.Services.LogService.writelog(" in Update " + newFile);

                //helperService.ResizeImage(newimage, uploadPath + image.id + ".ext", 1000, 1000, true);
                new image_handler().process(image.id, processed_image, newFile, image_handler.imageMethod.Constrain, 0, 0, 1000, image_handler.Dimensions.Width, true, "", image.get_meta("ext"));
            }

            ActiveRecordMediator <posting> .Save(image);

            if (events_id != 0)
            {
                posting events = ActiveRecordBase <posting> .Find(events_id);

                //events.images.Add(image);//FIX IT
                ActiveRecordMediator <posting> .Save(events);
            }

            if (ajax)
            {
                CancelView();
                CancelLayout();
                RenderText(image.id.ToString());
                return;
            }
            Flash["message"] = "Image Added";
            RedirectToAction("list");
        }
        /// <summary> </summary>
        public Thread StartTheThread(posting media, System.Drawing.Image processed_image, string tmp_File)
        {
            log.Info("StartTheThread for " + media.static_file + " with id " + media.id + " at path " + tmp_File);
            var t = new Thread(() => new image_handler().process(media.id, processed_image, tmp_File, image_handler.imageMethod.Constrain, 0, 0, 1000, image_handler.Dimensions.Width, true, "", media.get_meta("ext")));

            t.Start();
            return(t);
        }
Exemple #6
0
        /// <summary> </summary>
        public static String image(int id, int w, int h, int p, string m, bool protect, string pre, string mark, bool nocache)
        {
            posting image = ActiveRecordBase <posting> .Find(id);

            string uploads_path = file_info.site_uploads_path();

            string[] generalized_file_path = image.static_file.Split(new String[] { "uploads/", "images/" }, StringSplitOptions.RemoveEmptyEntries);
            string   file_path             = file_handler.normalize_path(uploads_path.Trim('/') + "/images/" + generalized_file_path[generalized_file_path.Length - 1].Trim('/'));

            String[] fileparts = file_path.Split('.');
            string   ext       = fileparts[fileparts.Length - 1];

            string cache_path  = file_info.site_cache_path().Trim('/') + "/uploads/images/";
            string cached_file = cache_path + generalized_file_path[generalized_file_path.Length - 1].Trim('/');

            string cache_url  = file_info.relative_site_cache_path().Trim('/') + "/uploads/images/";
            string cached_url = cache_url + generalized_file_path[generalized_file_path.Length - 1].Trim('/');


            if (String.IsNullOrWhiteSpace(m))
            {
                m = "constrain";
                w = 1000;//this will be site prefenece for max served iamges.
                h = 1000;
            }

            string arg = (!String.IsNullOrEmpty(pre) ? "_" + pre + "_" : "");

            arg += (w != 0 ? "w_" + w + "_" : "");
            arg += (h != 0 ? "h_" + h + "_" : "");
            arg += (p != 0 ? "p_" + p + "_" : "");
            arg += (protect != false ? "pro_true_" : "");
            arg += (!String.IsNullOrEmpty(m) ? "m_" + m + "_" : "");
            arg += (!String.IsNullOrEmpty(mark) ? "mark_" + mark + "_" : "");



            String[] c_file_parts     = cached_file.Split(new string[] { "." + ext }, StringSplitOptions.None);
            string   cached_file_path = c_file_parts[0] + id + arg + "." + ext;

            String[] c_cached_url    = cached_url.Split(new string[] { "." + ext }, StringSplitOptions.None);
            string   cached_file_url = c_cached_url[0] + id + arg + "." + ext;


            // if the process image doesn't Exist yet create it
            if (!File.Exists(cached_file_path))
            {
                System.Drawing.Image processed_image = null;
                try{
                    processed_image = System.Drawing.Image.FromFile(file_path);
                } catch (Exception ex) {
                    throw new IOException(ex.Message.Insert(ex.Message.Length, " " + file_path));
                }
                if (processed_image != null)
                {
                    //set some defaults
                    image_handler.imageMethod methodChoice = image_handler.imageMethod.Percent;
                    image_handler.Dimensions  dimensional  = image_handler.Dimensions.Width;

                    //choose medth of sizing and set their defaults
                    switch (m)
                    {
                    case "percent":
                        methodChoice = image_handler.imageMethod.Percent;
                        break;

                    case "constrain":
                        methodChoice = image_handler.imageMethod.Constrain;
                        dimensional  = w != 0 ? image_handler.Dimensions.Width : image_handler.Dimensions.Height;
                        break;

                    case "fixed":
                        methodChoice = image_handler.imageMethod.Fixed;
                        break;

                    case "crop":
                        methodChoice = image_handler.imageMethod.Crop;
                        break;
                    }
                    new image_handler().process(id, processed_image, cached_file_path, methodChoice, p, h, w, dimensional, protect, mark, image.get_meta("ext"));
                }
            }
            return(cached_file_url);
        }