Exemple #1
0
 private void ProcessResources(PDResources resources, string prefix, bool addKey)
 {
     if (resources != null)
     {
         Iterator iterator = resources.getXObjectNames().iterator();
         int      num      = 1;
         while (iterator.hasNext())
         {
             COSName cOSName = (COSName)iterator.next();
             string  str     = null;
             str = (!addKey ? this.GetUniqueFileName(prefix, ".jpg") : this.GetUniqueFileName(string.Concat(prefix, "_", num), ".jpg"));
             PDResources.OutputFileName = string.Concat(str, ".jpg");
             PDXObject xObject = resources.getXObject(cOSName);
             if (resources.isImageXObject(cOSName))
             {
                 PDImageXObject pDImageXObject = (PDImageXObject)xObject;
                 str = (!addKey ? this.GetUniqueFileName(prefix, pDImageXObject.getSuffix()) : this.GetUniqueFileName(string.Concat(prefix, "_", num), pDImageXObject.getSuffix()));
                 Console.WriteLine(string.Concat("Writing image:", str));
                 try
                 {
                     BufferedImage image = pDImageXObject.getImage();
                     ImageIO.write(image, "jpg", new java.io.File(string.Concat(str, ".jpg")));
                 }
                 catch (Exception exception)
                 {
                     Console.WriteLine("Could not write image: {0}.{1}{2}", str, Environment.NewLine, exception.Message);
                 }
             }
             else if (xObject is PDFormXObject)
             {
                 this.ProcessResources(((PDFormXObject)xObject).getResources(), prefix, addKey);
             }
         }
     }
 }
        private bool parseImage()

        {
            _image = ImageIO.read(_is);

            _width  = _image.getWidth();
            _height = _image.getHeight();

            TempStream  ts = new TempStream();
            WriteStream os = new WriteStream(ts);

            try {
                ImageIO.write(_image, "jpeg", os);
            } finally {
                os.close();
            }

            /*
             * os = Vfs.openWrite("file:/tmp/caucho/qa/test.jpg");
             * try {
             * ImageIO.write(_image, "jpeg", os);
             * } finally {
             * os.close();
             * }
             *
             * os = Vfs.openWrite("file:/tmp/caucho/qa/test.png");
             * try {
             * ImageIO.write(_image, "png", os);
             * } finally {
             * os.close();
             * }
             */

            return(parseImageJpeg(ts.openRead()));
        }
Exemple #3
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static String getChallangeAndWriteImage(org.patchca.service.CaptchaService service, String format, java.io.OutputStream os) throws java.io.IOException
        public static string getChallangeAndWriteImage(CaptchaService service, string format, OutputStream os)
        {
            Captcha captcha = service.Captcha;

            ImageIO.write(captcha.Image, format, os);
            return(captcha.Challenge);
        }
Exemple #4
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public void writeEnd() throws java.io.IOException
            public override void writeEnd()
            {
                if (!ImageIO.write(im, fileFormat, new File(fileName)))
                {
                    Console.WriteLine(string.Format("Cannot save image in format {0} using ImageIO: {1}", fileFormat, fileName));
                }
            }
Exemple #5
0
        /// <summary>
        /// Get a thumbnail of the document, if possible
        /// </summary>
        /// <param name="sizeX">The maximum X size of the thumbnail</param>
        /// <param name="sizeY">The maximum y size of the thumbnail</param>
        /// <param name="forceFullSize">True if the thumbnail should be exatly XxY pixels and False if the thumbnail
        /// should fit inside a XxY box but should maintain its aspect ratio</param>
        /// <returns>A JPEG byte thumbnail or null if the thumbnail can´t be generated</returns>
        public override byte[] GetThumbnail(int sizeX, int sizeY, bool forceFullSize)
        {
            // If we have no bytes then we can't do anything.
            if (Bytes == null || Bytes.Length == 0)
            {
                return(null);
            }

            try
            {
                org.pdfbox.pdfviewer.PageDrawer pagedrawer = new
                                                             org.pdfbox.pdfviewer.PageDrawer();

                java.io.ByteArrayInputStream byteStream = new java.io.ByteArrayInputStream(Bytes);
                PDDocument     doc   = PDDocument.load(byteStream);
                int            count = doc.getNumberOfPages();
                java.util.List pages = doc.getDocumentCatalog().getAllPages();
                if (pages.size() > 0)
                {
                    PDPage page = pagedrawer.getPage();
                    java.awt.image.BufferedImage  image = page.convertToImage();
                    java.io.ByteArrayOutputStream os    = new java.io.ByteArrayOutputStream();
                    ImageIO.write(image, "jpg", os);
                    byte[] data = os.toByteArray();
                    return(data);
                }
            }
            catch (Exception e)
            {
                log.Error("Failed to get the thumbnail from the PDF file " + Name, e);
            }

            return(null);
        }
 public static void save(BufferedImage image, string filename, string type)
 {
     try
     {
         ImageIO.write(image, type, new File(filename));
     }
     catch (IOException ex)
     {
         throw new Exception("IOException whle trying to save image file" + filename, ex);
     }
 }
Exemple #7
0
        //mouse released//
        private void jPanel2MouseReleased(MouseEvent evt)
        {
            currentX = evt.X;
            currentY = evt.Y;


            const double  SCALE = 0.1;
            BufferedImage bi    = new BufferedImage(32, 32, BufferedImage.TYPE_BYTE_GRAY);

            Graphics2D grph = (Graphics2D)bi.Graphics;

            grph.scale(SCALE, SCALE);

            grph.drawImage(canvas, 0, 0, null);
            grph.dispose();

            newPix = new double[32 * 32];
            pixels = bi.getRGB(0, 0, 32, 32, pixels, 0, 32);

            for (int i = 0; i < pixels.Length; i++)
            {
                newPix[i]  = 255 - (pixels[i] & 0xff);
                newPix[i] /= 255;
            }


            long start = DateTimeHelperClass.CurrentUnixTimeMillis();

            network.Input = newPix;
            network.calculate();
            Console.WriteLine("Execution time: " + (DateTimeHelperClass.CurrentUnixTimeMillis() - start) + " milliseconds");

            try
            {
                ImageIO.write(bi, "png", new File("number.png"));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }

            double[] networkOutput = network.Output;
            int      maxNeuronIdx  = Utils.maxIdx(networkOutput);

            ClassificationResult max = new ClassificationResult(maxNeuronIdx, networkOutput[maxNeuronIdx]);


            Console.WriteLine("New calculation:");
            Console.WriteLine("Class: " + max.ClassIdx);
            Console.WriteLine("Probability: " + max.NeuronOutput);

            label.Text = Convert.ToString(max.ClassIdx);
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static boolean saveImage(java.awt.image.BufferedImage paramBufferedImage, String paramString, int paramInt) throws java.io.IOException
        public static bool saveImage(BufferedImage paramBufferedImage, string paramString, int paramInt)
        {
            string str = "jpg";

            if (paramInt == 1)
            {
                str = "png";
            }
            else if (paramInt == 3)
            {
                str = "gif";
            }
            return(ImageIO.write(paramBufferedImage, str, new File(paramString)));
        }
Exemple #9
0
        protected internal virtual bool compareScreenshots(File expected, File result, File compare)
        {
            bool equals = false;

            try
            {
                System.Drawing.Bitmap expectedImg = ImageIO.read(expected);

                System.Drawing.Bitmap resultImg;
                try
                {
                    resultImg = ImageIO.read(result);
                }
                catch (Exception)
                {
                    // java.lang.RuntimeException: New BMP version not implemented yet.
                    resultImg = readBmp(result);
                }

                int width  = System.Math.Min(expectedImg.Width, resultImg.Width);
                int height = System.Math.Min(expectedImg.Height, resultImg.Height);
                System.Drawing.Bitmap compareImg = new System.Drawing.Bitmap(width, height, System.Drawing.Bitmap.TYPE_INT_RGB);
                equals = true;
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        int expectedColor = expectedImg.getRGB(x, y);
                        int resultColor   = resultImg.getRGB(x, y);
                        if (areColorsEqual(expectedColor, resultColor))
                        {
                            compareImg.setRGB(x, y, 0x000000);
                        }
                        else
                        {
                            compareImg.setRGB(x, y, 0xFF0000);
                            equals = false;
                        }
                    }
                }
                ImageIO.write(compareImg, "bmp", compare);
            }
            catch (IOException e)
            {
                error(string.Format("comparing screenshots {0}", e));
            }

            return(equals);
        }
Exemple #10
0
        /// <summary>
        /// Save the image to the file </summary>
        /// <param name="image"> should be cropped before the saving. Use OCRCropImage class </param>
        /// <param name="path"> path to the folder, ie C:/Users/.../ it should ended with / </param>
        /// <param name="letterName"> letter of the name </param>
        /// <param name="extension"> some of .png .jpg ... </param>
        public static void saveToFile(BufferedImage image, string path, string letterName, string extension)
        {
            string imagePath  = path + letterName + "." + extension;
            File   outputfile = new File(imagePath);

            try
            {
                ImageIO.write(image, extension, outputfile);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.ToString());
                Console.Write(ex.StackTrace);
            }
        }
Exemple #11
0
        public static BufferedImage binary(string textImageFile)
        {
            // load and convert the image into a usable format
            BufferedImage image = UtilImageIO.loadImage(textImageFile);

            // convert into a usable format
            ImageFloat32 input  = ConvertBufferedImage.convertFromSingle(image, null, typeof(ImageFloat32));
            ImageUInt8   binary = new ImageUInt8(input.width, input.height);
            ImageSInt32  label  = new ImageSInt32(input.width, input.height);

            // Select a global threshold using Otsu's method.
            double threshold = GThresholdImageOps.computeOtsu(input, 0, 256);

            // Apply the threshold to create a binary image
            ThresholdImageOps.threshold(input, binary, (float)threshold, true);

            // remove small blobs through erosion and dilation
            // The null in the input indicates that it should internally declare the work image it needs
            // this is less efficient, but easier to code.
            ImageUInt8 filtered = BinaryImageOps.erode8(binary, 1, null);

            filtered = BinaryImageOps.dilate8(filtered, 1, null);

            // get the binary image
            BufferedImage visualFiltered = VisualizeBinaryData.renderBinary(filtered, null);

            //write the negative image to a file
            File charFile = new File("whiteandblack.png");

            try
            {
                ImageIO.write(visualFiltered, "png", charFile);
            }
            catch (IOException ex)
            {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                Logger.getLogger(typeof(BinaryOps).FullName).log(Level.SEVERE, null, ex);
            }

            //return the positive image
            return(invertImage("whiteandblack.png"));
        }
Exemple #12
0
        /// <summary>
        /// Crop the part of an image with a white rectangle
        /// </summary>
        /// <returns> A cropped image File </returns>
        public virtual File crop(BufferedImage image)
        {
            // this will be coordinates of the upper left white pixel
            int upperLeftCornerx = int.MaxValue;
            int upperLeftCornery = int.MaxValue;
            //this will be coordinates of the lower right white pixel
            int lowerRightCornerx = int.MinValue;
            int lowerRightCornery = int.MinValue;

            //find the minimum and maximum white pixel coordinates
            for (int i = 0; i < image.Width; i++)
            {
                for (int j = 0; j < image.Height; j++)
                {
                    if (image.getRGB(i, j) == WHITE.RGB && (i < upperLeftCornerx && j < upperLeftCornery) || (i <= upperLeftCornerx && j < upperLeftCornery) || (i < upperLeftCornerx && j <= upperLeftCornery))
                    {
                        upperLeftCornerx = i;
                        upperLeftCornery = j;
                    }
                    if (image.getRGB(i, j) == WHITE.RGB && ((i > lowerRightCornerx && j >= lowerRightCornery) || (i >= lowerRightCornerx && j > lowerRightCornery) || (i > lowerRightCornerx && j >= lowerRightCornery)))
                    {
                        lowerRightCornerx = i;
                        lowerRightCornery = j;
                    }
                }
            }
            //crop the image to the white rectangle size
            BufferedImage croppedImage = image.getSubimage(upperLeftCornerx, upperLeftCornery, lowerRightCornerx - upperLeftCornerx, lowerRightCornery - upperLeftCornery);
            //make a file from that cropped image
            File cropFile = new File("croppedimage.png");

            try
            {
                ImageIO.write(croppedImage, "png", cropFile);
            }
            catch (IOException ex)
            {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                Logger.getLogger(typeof(OcrDemo).FullName).log(Level.SEVERE, null, ex);
            }
            return(cropFile);
        }
Exemple #13
0
        ///
        /// <summary>
        /// Inverts the image colors from negative to positive
        /// </summary>
        /// <returns> the image with inverted colors </returns>
        public static BufferedImage invertImage(string imageName)
        {
            // read the image file
            BufferedImage inputFile = null;

            try
            {
                inputFile = ImageIO.read(new File(imageName));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }

            // go through image pixels and reverse their color
            for (int x = 0; x < inputFile.Width; x++)
            {
                for (int y = 0; y < inputFile.Height; y++)
                {
                    int   rgba = inputFile.getRGB(x, y);
                    Color col  = new Color(rgba, true);
                    col = new Color(255 - col.Red, 255 - col.Green, 255 - col.Blue);
                    inputFile.setRGB(x, y, col.RGB);
                }
            }

            //write the image to a file blackandwhite.png
            try
            {
                File outputFile = new File("blackandwhite.png");
                ImageIO.write(inputFile, "png", outputFile);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
            return(inputFile);
        }
Exemple #14
0
        private void saveToFile(BufferedImage img, string letterName)
        {
            File          outputfile = new File(location + letterName + ".png");
            BufferedImage crop       = img;

            if (cropHeight != 0 || cropWidth != 0)
            {
                OCRCropImage ci = new OCRCropImage();
                ci.setDimension(cropWidth, cropHeight);
                crop = ci.processImage(img);
            }


            try
            {
                ImageIO.write(crop, "png", outputfile);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.ToString());
                Console.Write(ex.StackTrace);
            }
        }
Exemple #15
0
 public static void extractImageFromPDF(string paramString1, string paramString2, string paramString3)
 {
     try
     {
         if (!Directory.Exists(paramString2) || File.Exists(paramString2))
         {
             Directory.CreateDirectory(paramString2);
         }
         Document document = new Document();
         document.File = paramString1;
         System.Collections.IList list = document.getPageImages(0);
         foreach (Image image in list)
         {
             if (image != null)
             {
                 BufferedImage bufferedImage = (BufferedImage)image;
                 try
                 {
                     File file = new File(paramString2 + File.separator + paramString3 + ".PNG");
                     ImageIO.write(bufferedImage, "png", file);
                 }
                 catch (IOException iOException)
                 {
                     Console.WriteLine(iOException.ToString());
                     Console.Write(iOException.StackTrace);
                 }
                 image.flush();
             }
         }
         document.dispose();
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception.ToString());
         Console.Write(exception.StackTrace);
     }
 }
Exemple #16
0
        private System.Drawing.Bitmap readImage(int offset, int Length)
        {
            int currentPosition = tell();

            seek(pImgData + offset);
            sbyte[] buffer = readBytes(Length);
            seek(currentPosition);

            System.IO.Stream imageInputStream           = new System.IO.MemoryStream(buffer);
            System.Drawing.Bitmap System.Drawing.Bitmap = null;
            try
            {
                System.Drawing.Bitmap = ImageIO.read(imageInputStream);
                imageInputStream.Close();

                // Add an alpha color channel if not available
                if (!System.Drawing.Bitmap.ColorModel.hasAlpha())
                {
                    System.Drawing.Bitmap System.Drawing.BitmapWithAlpha = new System.Drawing.Bitmap(System.Drawing.Bitmap.Width, System.Drawing.Bitmap.Height, System.Drawing.Bitmap.TYPE_INT_ARGB);
                    Graphics2D g = System.Drawing.BitmapWithAlpha.createGraphics();
                    g.drawImage(System.Drawing.Bitmap, 0, 0, null);
                    g.dispose();
                    System.Drawing.Bitmap = System.Drawing.BitmapWithAlpha;
                }

                if (dumpImages)
                {
                    ImageIO.write(System.Drawing.Bitmap, "png", new File(string.Format("tmp/Image0x{0:X}.png", offset)));
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(string.Format("Error reading image from RCO at 0x{0:X}, Length=0x{1:X}", offset, Length), e);
            }

            return(System.Drawing.Bitmap);
        }
Exemple #17
0
        public virtual void save(File f)
        {
            this.filename = f.getName();
            if (this.frame != null)
            {
                this.frame.setTitle(this.filename);
            }
            string text = java.lang.String.instancehelper_substring(this.filename, java.lang.String.instancehelper_lastIndexOf(this.filename, 46) + 1);

            text = java.lang.String.instancehelper_toLowerCase(text);
            if (!java.lang.String.instancehelper_equals(text, "jpg"))
            {
                if (!java.lang.String.instancehelper_equals(text, "png"))
                {
                    [email protected]("Error: filename must end in .jpg or .png");
                    return;
                }
            }
            IOException ex;

            try
            {
                ImageIO.write(this.image, text, f);
            }
            catch (IOException arg_74_0)
            {
                ex = ByteCodeHelper.MapException <IOException>(arg_74_0, ByteCodeHelper.MapFlags.NoRemapping);
                goto IL_7E;
            }
            return;

IL_7E:
            IOException this2 = ex;

            Throwable.instancehelper_printStackTrace(this2);
        }
        private void CommitIconToWS()
        {
            try
            {
                logger.Info("post icon");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(GetIcon(), "png", baos);
                baos.flush();
                byte[] imageInByte = baos.toByteArray();
                baos.close();

                String resource = REQUEST.API_PATH_V1
                        + REQUEST.CLASSES.PATH
                        + GetName() + "/"
                        + REQUEST.CLASSES.ICON.PATH;

                HttpURLConnection connection = ds.getHTTPConnection().getPostIconConnection(resource);


                OutputStream os = connection.getOutputStream();

                os.write(imageInByte);
                os.flush();
                os.close();

                //
                int responseCode = connection.getResponseCode();
                logger.Error("commit icon: {}", responseCode);



                catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Exemple #19
0
 public static sbyte[] imageToBase64(ImageIcon paramImageIcon, int paramInt)
 {
     try
     {
         string str = "jpg";
         if (paramInt == 1)
         {
             str = "png";
         }
         else if (paramInt == 3)
         {
             str = "gif";
         }
         BufferedImage bufferedImage         = (BufferedImage)paramImageIcon.Image;
         MemoryStream  byteArrayOutputStream = new MemoryStream();
         ImageIO.write(bufferedImage, str, byteArrayOutputStream);
         sbyte[] arrayOfByte = byteArrayOutputStream.toByteArray();
         return(Base64.encode(arrayOfByte));
     }
     catch (IOException)
     {
         return(null);
     }
 }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void saveToFile(java.awt.image.BufferedImage img, String name) throws java.io.FileNotFoundException, java.io.IOException
        public virtual void saveToFile(BufferedImage img, string name)
        {
            File outputfile = new File("C:/Users/Mihailo/Documents/NetBeansProjects/ImagePreprocessing/Segmented_letters/" + name + ".jpg");

            ImageIO.write(img, "jpg", outputfile);
        }