public NikseBitmap(NikseBitmap input)
 {
     Width = input.Width;
     Height = input.Height;
     _bitmapData = new byte[input._bitmapData.Length];
     Buffer.BlockCopy(input._bitmapData, 0, _bitmapData, 0, _bitmapData.Length);
 }
Esempio n. 2
0
 public BinaryOcrBitmap(NikseBitmap nbmp, bool italic, int expandCount, string text, int x, int y)
 {
     InitializeViaNikseBmp(nbmp);
     Italic = italic;
     ExpandCount = expandCount;
     Text = text;
     X = x;
     Y = y;
 }
Esempio n. 3
0
        public void TestMethodBinOcrSaveLoad()
        {
            string tempFileName = Path.GetTempFileName();
            var db = new BinaryOcrDb(tempFileName);
            var nbmp = new NikseBitmap(2, 2);
            nbmp.SetPixel(0, 0, Color.Transparent);
            nbmp.SetPixel(1, 0, Color.Transparent);
            nbmp.SetPixel(1, 0, Color.Transparent);
            nbmp.SetPixel(1, 1, Color.White);

            var bob = new BinaryOcrBitmap(nbmp);
            bob.Text = "Debug";
            db.Add(bob);

            nbmp.SetPixel(0, 0, Color.White);
            var bob2 = new BinaryOcrBitmap(nbmp);
            bob2.X = 2;
            bob2.Y = 4;
            bob2.Text = "tt";
            bob2.Italic = true;
            bob2.ExpandCount = 2;
            bob2.ExpandedList = new System.Collections.Generic.List<BinaryOcrBitmap>();
            bob2.ExpandedList.Add(bob2);
            db.Add(bob2);
            db.Save();

            db = new BinaryOcrDb(tempFileName, true);
            Assert.IsTrue(db.CompareImages.Count == 1);
            Assert.IsTrue(db.CompareImagesExpanded.Count == 1);

            Assert.IsTrue(bob.Width == db.CompareImages[0].Width);
            Assert.IsTrue(bob.Height == db.CompareImages[0].Height);
            Assert.IsTrue(bob.NumberOfColoredPixels == db.CompareImages[0].NumberOfColoredPixels);
            Assert.IsTrue(bob.Hash == db.CompareImages[0].Hash);
            Assert.IsTrue(bob.Italic == db.CompareImages[0].Italic);
            Assert.IsTrue(bob.ExpandCount == db.CompareImages[0].ExpandCount);
            Assert.IsTrue(bob.Text == db.CompareImages[0].Text);

            Assert.IsTrue(bob2.Width == db.CompareImagesExpanded[0].Width);
            Assert.IsTrue(bob2.Height == db.CompareImagesExpanded[0].Height);
            Assert.IsTrue(bob2.NumberOfColoredPixels == db.CompareImagesExpanded[0].NumberOfColoredPixels);
            Assert.IsTrue(bob2.Hash == db.CompareImagesExpanded[0].Hash);
            Assert.IsTrue(bob2.Italic == db.CompareImagesExpanded[0].Italic);
            Assert.IsTrue(bob2.ExpandCount == db.CompareImagesExpanded[0].ExpandCount);
            Assert.IsTrue(bob2.Text == db.CompareImagesExpanded[0].Text);
            Assert.IsTrue(bob2.X == db.CompareImagesExpanded[0].X);
            Assert.IsTrue(bob2.Y == db.CompareImagesExpanded[0].Y);

            try
            {
                File.Delete(tempFileName);
            }
            catch
            {
            }
        }
Esempio n. 4
0
 public ManagedBitmap(NikseBitmap nbmp)
 {
     Width = nbmp.Width;
     Height = nbmp.Height;
     _colors = new Color[Width * Height];
     for (int y = 0; y < Height; y++)
     {
         for (int x = 0; x < Width; x++)
         {
             SetPixel(x, y, nbmp.GetPixel(x, y));
         }
     }
 }
Esempio n. 5
0
 public ManagedBitmap(Bitmap oldBitmap)
 {
     NikseBitmap nbmp = new NikseBitmap(oldBitmap);
     Width = nbmp.Width;
     Height = nbmp.Height;
     _colors = new Color[Width * Height];
     for (int y = 0; y < Height; y++)
     {
         for (int x = 0; x < Width; x++)
         {
             this.SetPixel(x, y, nbmp.GetPixel(x, y));
         }
     }
 }
        private void listBoxSubtitles_SelectedIndexChanged(object sender, EventArgs e)
        {
            int idx = listBoxSubtitles.SelectedIndex;
            if (idx < 0)
                return;

            int pid = _tsParser.SubtitlePacketIds[listBoxTracks.SelectedIndex];
            var list = _tsParser.GetDvbSubtitles(pid);

            var dvbBmp = list[idx].GetActiveImage();
            var nDvbBmp = new NikseBitmap(dvbBmp);
            nDvbBmp.CropTopTransparent(2);
            nDvbBmp.CropTransparentSidesAndBottom(2, true);
            dvbBmp.Dispose();
            var oldImage = pictureBox1.Image;
            pictureBox1.Image = nDvbBmp.GetBitmap();
            if (oldImage != null)
                oldImage.Dispose();
        }
Esempio n. 7
0
        public void TestMethodBinOcrSaveLoadTestExceptions()
        {
            string tempFileName = Path.GetTempFileName();
            var db = new BinaryOcrDb(tempFileName);
            var nbmp = new NikseBitmap(2, 2);
            nbmp.SetPixel(0, 0, Color.Transparent);
            nbmp.SetPixel(1, 0, Color.Transparent);
            nbmp.SetPixel(1, 0, Color.Transparent);
            nbmp.SetPixel(1, 1, Color.White);

            var bob = new BinaryOcrBitmap(nbmp);
            bob.Text = "S";
            db.Add(bob);

            nbmp.SetPixel(0, 0, Color.White);
            var bob2 = new BinaryOcrBitmap(nbmp);
            bob2.X = 2;
            bob2.Y = 4;
            bob2.Text = null;
            bob2.Italic = true;
            bob2.ExpandCount = 3;
            bob2.ExpandedList = new System.Collections.Generic.List<BinaryOcrBitmap>();
            bob2.ExpandedList.Add(bob2);
            try
            {
                db.Add(bob2);
            }
            catch
            {
                return;
            }
            Assert.Fail();

            try
            {
                File.Delete(tempFileName);
            }
            catch
            {
            }
        }
Esempio n. 8
0
        private static void MakeBluRaySupImage(MakeBitmapParameter param)
        {
            var brSub = new BluRaySupPicture
            {
                StartTime = (long)param.P.StartTime.TotalMilliseconds,
                EndTime = (long)param.P.EndTime.TotalMilliseconds,
                Width = param.ScreenWidth,
                Height = param.ScreenHeight,
                IsForced = param.Forced
            };
            if (param.FullFrame)
            {
                var nbmp = new NikseBitmap(param.Bitmap);
                nbmp.ReplaceTransparentWith(param.FullFrameBackgroundcolor);
                using (var bmp = nbmp.GetBitmap())
                {
                    int top = param.ScreenHeight - (param.Bitmap.Height + param.BottomMargin);
                    int left = (param.ScreenWidth - param.Bitmap.Width) / 2;

                    var b = new NikseBitmap(param.ScreenWidth, param.ScreenHeight);
                    {
                        b.Fill(param.FullFrameBackgroundcolor);
                        using (var fullSize = b.GetBitmap())
                        {
                            if (param.Alignment == ContentAlignment.BottomLeft || param.Alignment == ContentAlignment.MiddleLeft || param.Alignment == ContentAlignment.TopLeft)
                                left = param.LeftRightMargin;
                            else if (param.Alignment == ContentAlignment.BottomRight || param.Alignment == ContentAlignment.MiddleRight || param.Alignment == ContentAlignment.TopRight)
                                left = param.ScreenWidth - param.Bitmap.Width - param.LeftRightMargin;
                            if (param.Alignment == ContentAlignment.TopLeft || param.Alignment == ContentAlignment.TopCenter || param.Alignment == ContentAlignment.TopRight)
                                top = param.BottomMargin;
                            if (param.Alignment == ContentAlignment.MiddleLeft || param.Alignment == ContentAlignment.MiddleCenter || param.Alignment == ContentAlignment.MiddleRight)
                                top = param.ScreenHeight - (param.Bitmap.Height / 2);

                            using (var g = Graphics.FromImage(fullSize))
                            {
                                g.DrawImage(bmp, left, top);
                                g.Dispose();
                            }
                            param.Buffer = BluRaySupPicture.CreateSupFrame(brSub, fullSize, param.FramesPerSeconds, 0, 0, ContentAlignment.BottomCenter);
                        }
                    }
                }
            }
            else
            {
                param.Buffer = BluRaySupPicture.CreateSupFrame(brSub, param.Bitmap, param.FramesPerSeconds, param.BottomMargin, param.LeftRightMargin, param.Alignment);
            }
        }
Esempio n. 9
0
        private static NikseBitmap Make3DTopBottom(MakeBitmapParameter parameter, NikseBitmap nbmp)
        {
            Bitmap singleBmp = nbmp.GetBitmap();
            Bitmap singleHalfBmp = ScaleToHalfHeight(singleBmp);
            singleBmp.Dispose();
            var topBottomBmp = new Bitmap(parameter.ScreenWidth, parameter.ScreenHeight - parameter.BottomMargin);
            int singleHeight = parameter.ScreenHeight / 2;
            int leftM = (parameter.ScreenWidth / 2) - (singleHalfBmp.Width / 2);

            using (Graphics gTopBottom = Graphics.FromImage(topBottomBmp))
            {
                gTopBottom.DrawImage(singleHalfBmp, leftM + parameter.Depth3D, singleHeight - singleHalfBmp.Height - parameter.BottomMargin);
                gTopBottom.DrawImage(singleHalfBmp, leftM - parameter.Depth3D, parameter.ScreenHeight - parameter.BottomMargin - singleHalfBmp.Height);
            }
            nbmp = new NikseBitmap(topBottomBmp);
            if (parameter.BackgroundColor == Color.Transparent)
            {
                nbmp.CropTop(2, Color.Transparent);
                nbmp.CropTransparentSidesAndBottom(2, false);
            }
            else
            {
                nbmp.CropTop(4, parameter.BackgroundColor);
                nbmp.CropSidesAndBottom(4, parameter.BackgroundColor, false);
            }
            return nbmp;
        }
Esempio n. 10
0
        private static Bitmap GenerateImageFromTextWithStyleInner(MakeBitmapParameter parameter)
        {
            string text = parameter.P.Text;

            text = Utilities.RemoveSsaTags(text);

            text = text.Replace("<I>", "<i>");
            text = text.Replace("</I>", "</i>");
            text = HtmlUtil.FixInvalidItalicTags(text);

            text = text.Replace("<B>", "<b>");
            text = text.Replace("</B>", "</b>");

            // no support for underline
            text = HtmlUtil.RemoveOpenCloseTags(text, HtmlUtil.TagUnderline);

            Font font = null;
            Bitmap bmp = null;
            try
            {
                font = SetFont(parameter, parameter.SubtitleFontSize);
                var lineHeight = parameter.LineHeight; // (textSize.Height * 0.64f);

                SizeF textSize;
                using (var bmpTemp = new Bitmap(1, 1))
                using (var g = Graphics.FromImage(bmpTemp))
                {
                    textSize = g.MeasureString(HtmlUtil.RemoveHtmlTags(text), font);
                }
                int sizeX = (int)(textSize.Width * 1.8) + 150;
                int sizeY = (int)(textSize.Height * 0.9) + 50;
                if (sizeX < 1)
                    sizeX = 1;
                if (sizeY < 1)
                    sizeY = 1;
                if (parameter.BackgroundColor != Color.Transparent)
                {
                    var nbmpTemp = new NikseBitmap(sizeX, sizeY);
                    nbmpTemp.Fill(parameter.BackgroundColor);
                    bmp = nbmpTemp.GetBitmap();
                }
                else
                {
                    bmp = new Bitmap(sizeX, sizeY);
                }

                // align lines with gjpqy, a bit lower
                var lines = text.SplitToLines();
                int baseLinePadding = 13;
                if (parameter.SubtitleFontSize < 30)
                    baseLinePadding = 12;
                if (parameter.SubtitleFontSize < 25)
                    baseLinePadding = 9;
                if (lines.Length > 0)
                {
                    var lastLine = lines[lines.Length - 1];
                    if (lastLine.Contains(new[] { 'g', 'j', 'p', 'q', 'y', ',', 'ý', 'ę', 'ç', 'Ç' }))
                    {
                        var textNoBelow = lastLine.Replace('g', 'a').Replace('j', 'a').Replace('p', 'a').Replace('q', 'a').Replace('y', 'a').Replace(',', 'a').Replace('ý', 'a').Replace('ę', 'a').Replace('ç', 'a').Replace('Ç', 'a');
                        baseLinePadding -= (int)Math.Round((TextDraw.MeasureTextHeight(font, lastLine, parameter.SubtitleFontBold) - TextDraw.MeasureTextHeight(font, textNoBelow, parameter.SubtitleFontBold)));
                    }
                    else
                    {
                        baseLinePadding += 1;
                    }
                    if (baseLinePadding < 0)
                        baseLinePadding = 0;
                }

                // TODO: Better baseline - test http://bobpowell.net/formattingtext.aspx
                //float baselineOffset=font.SizeInPoints/font.FontFamily.GetEmHeight(font.Style)*font.FontFamily.GetCellAscent(font.Style);
                //float baselineOffsetPixels = g.DpiY/72f*baselineOffset;
                //baseLinePadding = (int)Math.Round(baselineOffsetPixels);

                var lefts = new List<float>();
                if (text.Contains("<font", StringComparison.OrdinalIgnoreCase) || text.Contains("<i>", StringComparison.OrdinalIgnoreCase) || text.Contains("<b>", StringComparison.OrdinalIgnoreCase))
                {
                    bool tempItalicOn = false;
                    bool tempBoldOn = false;
                    foreach (string line in text.SplitToLines())
                    {
                        var tempLine = HtmlUtil.RemoveOpenCloseTags(line, HtmlUtil.TagFont);

                        if (tempItalicOn)
                            tempLine = "<i>" + tempLine;

                        if (tempBoldOn)
                            tempLine = "<b>" + tempLine;

                        if (tempLine.Contains("<i>") && !tempLine.Contains("</i>"))
                            tempItalicOn = true;

                        if (tempLine.Contains("<b>") && !tempLine.Contains("</b>"))
                            tempBoldOn = true;

                        if (parameter.AlignLeft)
                            lefts.Add(5);
                        else if (parameter.AlignRight)
                            lefts.Add(bmp.Width - CalcWidthViaDraw(tempLine, parameter) - 15); // calculate via drawing+crop
                        else
                            lefts.Add((float)((bmp.Width - CalcWidthViaDraw(tempLine, parameter) + 5.0) / 2.0)); // calculate via drawing+crop

                        if (line.Contains("</i>"))
                            tempItalicOn = false;

                        if (line.Contains("</b>"))
                            tempBoldOn = false;
                    }
                }
                else
                {
                    foreach (var line in HtmlUtil.RemoveOpenCloseTags(text, HtmlUtil.TagItalic, HtmlUtil.TagFont).SplitToLines())
                    {
                        if (parameter.AlignLeft)
                            lefts.Add(5);
                        else if (parameter.AlignRight)
                            lefts.Add(bmp.Width - (TextDraw.MeasureTextWidth(font, line, parameter.SubtitleFontBold) + 15));
                        else
                            lefts.Add((float)((bmp.Width - TextDraw.MeasureTextWidth(font, line, parameter.SubtitleFontBold) + 15) / 2.0));
                    }
                }

                var sf = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Near };

                using (var g = Graphics.FromImage(bmp))
                {
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    if (parameter.SimpleRendering)
                    {
                        if (text.StartsWith("<font ", StringComparison.Ordinal) && Utilities.CountTagInText(text, "<font") == 1)
                        {
                            parameter.SubtitleColor = Utilities.GetColorFromFontString(text, parameter.SubtitleColor);
                        }

                        text = HtmlUtil.RemoveHtmlTags(text, true); // TODO: Perhaps check single color...
                        var brush = new SolidBrush(parameter.BorderColor);
                        int x = 3;
                        const int y = 3;
                        sf.Alignment = StringAlignment.Near;
                        if (parameter.AlignLeft)
                        {
                            sf.Alignment = StringAlignment.Near;
                        }
                        else if (parameter.AlignRight)
                        {
                            sf.Alignment = StringAlignment.Far;
                            x = parameter.ScreenWidth - 5;
                        }
                        else
                        {
                            sf.Alignment = StringAlignment.Center;
                            x = parameter.ScreenWidth / 2;
                        }

                        bmp = new Bitmap(parameter.ScreenWidth, sizeY);

                        Graphics surface = Graphics.FromImage(bmp);
                        surface.CompositingQuality = CompositingQuality.HighSpeed;
                        surface.InterpolationMode = InterpolationMode.Default;
                        surface.SmoothingMode = SmoothingMode.HighSpeed;
                        surface.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                        for (int j = 0; j < parameter.BorderWidth; j++)
                        {
                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y + 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y + 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y + 1 + j }, sf);

                            surface.DrawString(text, font, brush, new PointF { X = x - j, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j, Y = y + 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j + 1, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j + 1, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j + 1, Y = y + 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j - 1, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j - 1, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j - 1, Y = y + 1 + j }, sf);

                            surface.DrawString(text, font, brush, new PointF { X = x - j, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j, Y = y + 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j + 1, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j + 1, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j + 1, Y = y + 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j - 1, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j - 1, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - j - 1, Y = y + 1 - j }, sf);

                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y + 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y + 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y + 1 - j }, sf);

                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j, Y = y + 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j + 1, Y = y + 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y - 1 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y - 0 + j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + j - 1, Y = y + 1 + j }, sf);

                            surface.DrawString(text, font, brush, new PointF { X = x, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x, Y = y + 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + 1, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + 1, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x + 1, Y = y + 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - 1, Y = y - 1 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - 1, Y = y - 0 - j }, sf);
                            surface.DrawString(text, font, brush, new PointF { X = x - 1, Y = y + 1 - j }, sf);
                        }
                        brush.Dispose();
                        brush = new SolidBrush(parameter.SubtitleColor);
                        surface.CompositingQuality = CompositingQuality.HighQuality;
                        surface.SmoothingMode = SmoothingMode.HighQuality;
                        surface.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        surface.DrawString(text, font, brush, new PointF { X = x, Y = y }, sf);
                        surface.Dispose();
                        brush.Dispose();
                    }
                    else
                    {
                        var path = new GraphicsPath();
                        var sb = new StringBuilder();
                        bool isItalic = false;
                        bool isBold = parameter.SubtitleFontBold;
                        float left = 5;
                        if (lefts.Count > 0)
                            left = lefts[0];
                        float top = 5;
                        bool newLine = false;
                        int lineNumber = 0;
                        float leftMargin = left;
                        int newLinePathPoint = -1;
                        Color c = parameter.SubtitleColor;
                        var colorStack = new Stack<Color>();
                        var lastText = new StringBuilder();
                        int numberOfCharsOnCurrentLine = 0;
                        for (var i = 0; i < text.Length; i++)
                        {
                            if (text.Substring(i).StartsWith("<font ", StringComparison.OrdinalIgnoreCase))
                            {
                                float addLeft = 0;
                                int oldPathPointIndex = path.PointCount;
                                if (oldPathPointIndex < 0)
                                    oldPathPointIndex = 0;

                                if (sb.Length > 0)
                                {
                                    lastText.Append(sb);
                                    TextDraw.DrawText(font, sf, path, sb, isItalic, isBold || parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                                }
                                if (path.PointCount > 0)
                                {
                                    var list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                                    for (int k = oldPathPointIndex; k < list.Length; k++)
                                    {
                                        if (list[k].X > addLeft)
                                            addLeft = list[k].X;
                                    }
                                }
                                if (path.PointCount == 0)
                                    addLeft = left;
                                else if (addLeft < 0.01)
                                    addLeft = left + 2;
                                left = addLeft;

                                DrawShadowAndPath(parameter, g, path);
                                var p2 = new SolidBrush(c);
                                g.FillPath(p2, path);
                                p2.Dispose();
                                path.Reset();
                                path = new GraphicsPath();
                                sb = new StringBuilder();

                                int endIndex = text.Substring(i).IndexOf('>');
                                if (endIndex < 0)
                                {
                                    i += 9999;
                                }
                                else
                                {
                                    string fontContent = text.Substring(i, endIndex);
                                    if (fontContent.Contains(" color="))
                                    {
                                        string[] arr = fontContent.Substring(fontContent.IndexOf(" color=", StringComparison.Ordinal) + 7).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                        if (arr.Length > 0)
                                        {
                                            string fontColor = arr[0].Trim('\'').Trim('"').Trim('\'');
                                            try
                                            {
                                                colorStack.Push(c); // save old color
                                                if (fontColor.StartsWith("rgb(", StringComparison.Ordinal))
                                                {
                                                    arr = fontColor.Remove(0, 4).TrimEnd(')').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                                    c = Color.FromArgb(int.Parse(arr[0]), int.Parse(arr[1]), int.Parse(arr[2]));
                                                }
                                                else
                                                {
                                                    c = ColorTranslator.FromHtml(fontColor);
                                                }
                                            }
                                            catch
                                            {
                                                c = parameter.SubtitleColor;
                                            }
                                        }
                                    }
                                    i += endIndex;
                                }
                            }
                            else if (text.Substring(i).StartsWith("</font>", StringComparison.OrdinalIgnoreCase))
                            {
                                if (text.Substring(i).ToLower().Replace("</font>", string.Empty).Length > 0)
                                {
                                    if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                                    {
                                        string t = sb.ToString();
                                        sb.Clear();
                                        sb.Append(' ');
                                        sb.Append(t);
                                    }

                                    float addLeft = 0;
                                    int oldPathPointIndex = path.PointCount - 1;
                                    if (oldPathPointIndex < 0)
                                        oldPathPointIndex = 0;
                                    if (sb.Length > 0)
                                    {
                                        if (lastText.Length > 0 && left > 2)
                                            left -= 1.5f;

                                        lastText.Append(sb);

                                        TextDraw.DrawText(font, sf, path, sb, isItalic, isBold || parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                                    }
                                    if (path.PointCount > 0)
                                    {
                                        var list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                                        for (int k = oldPathPointIndex; k < list.Length; k++)
                                        {
                                            if (list[k].X > addLeft)
                                                addLeft = list[k].X;
                                        }
                                    }
                                    if (addLeft < 0.01)
                                        addLeft = left + 2;
                                    left = addLeft;

                                    DrawShadowAndPath(parameter, g, path);
                                    g.FillPath(new SolidBrush(c), path);
                                    path.Reset();
                                    sb = new StringBuilder();
                                    if (colorStack.Count > 0)
                                        c = colorStack.Pop();
                                    if (left >= 3)
                                        left -= 2.5f;
                                }
                                i += 6;
                            }
                            else if (text.Substring(i).StartsWith("<i>", StringComparison.OrdinalIgnoreCase))
                            {
                                if (sb.Length > 0)
                                {
                                    lastText.Append(sb);
                                    TextDraw.DrawText(font, sf, path, sb, isItalic, isBold || parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                                }
                                isItalic = true;
                                i += 2;
                            }
                            else if (text.Substring(i).StartsWith("</i>", StringComparison.OrdinalIgnoreCase) && isItalic)
                            {
                                if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                                {
                                    string t = sb.ToString();
                                    sb.Clear();
                                    sb.Append(' ');
                                    sb.Append(t);
                                }
                                lastText.Append(sb);
                                TextDraw.DrawText(font, sf, path, sb, isItalic, isBold || parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                                isItalic = false;
                                i += 3;
                            }
                            else if (text.Substring(i).StartsWith("<b>", StringComparison.OrdinalIgnoreCase))
                            {
                                if (sb.Length > 0)
                                {
                                    lastText.Append(sb);
                                    TextDraw.DrawText(font, sf, path, sb, isItalic, isBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                                }
                                isBold = true;
                                i += 2;
                            }
                            else if (text.Substring(i).StartsWith("</b>", StringComparison.OrdinalIgnoreCase) && isBold)
                            {
                                if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                                {
                                    string t = sb.ToString();
                                    sb.Clear();
                                    sb.Append(' ');
                                    sb.Append(t);
                                }
                                lastText.Append(sb);
                                TextDraw.DrawText(font, sf, path, sb, isItalic, isBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                                isBold = false;
                                i += 3;
                            }
                            else if (text.Substring(i).StartsWith(Environment.NewLine, StringComparison.Ordinal))
                            {
                                lastText.Append(sb);
                                TextDraw.DrawText(font, sf, path, sb, isItalic, isBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);

                                top += lineHeight;
                                newLine = true;
                                i += Environment.NewLine.Length - 1;
                                lineNumber++;
                                if (lineNumber < lefts.Count)
                                {
                                    leftMargin = lefts[lineNumber];
                                    left = leftMargin;
                                }
                                numberOfCharsOnCurrentLine = 0;
                            }
                            else
                            {
                                if (numberOfCharsOnCurrentLine != 0 || text[i] != ' ')
                                {
                                    sb.Append(text[i]);
                                    numberOfCharsOnCurrentLine++;
                                }
                            }
                        }
                        if (sb.Length > 0)
                            TextDraw.DrawText(font, sf, path, sb, isItalic, isBold || parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);

                        DrawShadowAndPath(parameter, g, path);
                        g.FillPath(new SolidBrush(c), path);
                    }
                }
                sf.Dispose();

                var nbmp = new NikseBitmap(bmp);
                if (parameter.BackgroundColor == Color.Transparent)
                {
                    nbmp.CropTransparentSidesAndBottom(baseLinePadding, true);
                    nbmp.CropTransparentSidesAndBottom(2, false);
                }
                else
                {
                    nbmp.CropSidesAndBottom(4, parameter.BackgroundColor, true);
                    nbmp.CropTop(4, parameter.BackgroundColor);
                }

                if (nbmp.Width > parameter.ScreenWidth)
                {
                    parameter.Error = "#" + parameter.P.Number.ToString(CultureInfo.InvariantCulture) + ": " + nbmp.Width.ToString(CultureInfo.InvariantCulture) + " > " + parameter.ScreenWidth.ToString(CultureInfo.InvariantCulture);
                }

                if (parameter.Type3D == 1) // Half-side-by-side 3D
                {
                    Bitmap singleBmp = nbmp.GetBitmap();
                    Bitmap singleHalfBmp = ScaleToHalfWidth(singleBmp);
                    singleBmp.Dispose();
                    var sideBySideBmp = new Bitmap(parameter.ScreenWidth, singleHalfBmp.Height);
                    int singleWidth = parameter.ScreenWidth / 2;
                    int singleLeftMargin = (singleWidth - singleHalfBmp.Width) / 2;

                    using (Graphics gSideBySide = Graphics.FromImage(sideBySideBmp))
                    {
                        gSideBySide.DrawImage(singleHalfBmp, singleLeftMargin + parameter.Depth3D, 0);
                        gSideBySide.DrawImage(singleHalfBmp, singleWidth + singleLeftMargin - parameter.Depth3D, 0);
                    }
                    nbmp = new NikseBitmap(sideBySideBmp);
                    if (parameter.BackgroundColor == Color.Transparent)
                        nbmp.CropTransparentSidesAndBottom(2, true);
                    else
                        nbmp.CropSidesAndBottom(4, parameter.BackgroundColor, true);
                }
                else if (parameter.Type3D == 2) // Half-Top/Bottom 3D
                {
                    nbmp = Make3DTopBottom(parameter, nbmp);
                }
                return nbmp.GetBitmap();
            }
            finally
            {
                if (font != null)
                {
                    font.Dispose();
                }
                if (bmp != null)
                {
                    bmp.Dispose();
                }
            }
        }
        private void buttonAddBetterMatch_Click(object sender, EventArgs e)
        {
            if (listBoxInspectItems.SelectedIndex < 0)
                return;

            if (listBoxInspectItems.Items[listBoxInspectItems.SelectedIndex].ToString() == textBoxText.Text)
            {
                textBoxText.SelectAll();
                textBoxText.Focus();
                return;
            }

            if (_selectedCompareBinaryOcrBitmap != null || (_binOcrDb != null && _selectedMatch.Text == Configuration.Settings.Language.VobSubOcr.NoMatch))
            {
                var nbmp = new NikseBitmap((pictureBoxInspectItem.Image as Bitmap));
                int x = 0;
                int y = 0;
                if (_selectedMatch != null && _selectedMatch.ImageSplitterItem != null)
                {
                    x = _selectedMatch.X;
                    y = _selectedMatch.Y;
                }
                var bob = new BinaryOcrBitmap(nbmp, checkBoxItalic.Checked, 0, textBoxText.Text, x, y);
                _binOcrDb.Add(bob);

                int index = listBoxInspectItems.SelectedIndex;
                _matches[index].Name = bob.Key;
                _matches[index].ExpandCount = 0;
                _matches[index].Italic = checkBoxItalic.Checked;
                _matches[index].Text = textBoxText.Text;
                listBoxInspectItems.Items.Clear();
                for (int i = 0; i < _matches.Count; i++)
                    listBoxInspectItems.Items.Add(_matches[i].Text);
                listBoxInspectItems.SelectedIndex = index;
                listBoxInspectItems_SelectedIndexChanged(null, null);
                ShowCount();
                return;
            }

            if (_selectedCompareNode != null)
            {
                XmlNode newNode = ImageCompareDocument.CreateElement("Item");
                XmlAttribute text = newNode.OwnerDocument.CreateAttribute("Text");
                text.InnerText = textBoxText.Text;
                newNode.Attributes.Append(text);

                string databaseName = Path.Combine(_directoryPath, "Images.db");
                FileStream f;
                long pos;
                if (!File.Exists(databaseName))
                {
                    using (f = new FileStream(databaseName, FileMode.Create))
                    {
                        pos = f.Position;
                        new ManagedBitmap(pictureBoxInspectItem.Image as Bitmap).AppendToStream(f);
                    }
                }
                else
                {
                    using (f = new FileStream(databaseName, FileMode.Append))
                    {
                        pos = f.Position;
                        new ManagedBitmap(pictureBoxInspectItem.Image as Bitmap).AppendToStream(f);
                    }
                }
                string name = pos.ToString(CultureInfo.InvariantCulture);
                newNode.InnerText = name;

                SetItalic(newNode);
                ImageCompareDocument.DocumentElement.AppendChild(newNode);

                int index = listBoxInspectItems.SelectedIndex;
                _matches[index].Name = name;
                _matches[index].ExpandCount = 0;
                _matches[index].Italic = checkBoxItalic.Checked;
                _matches[index].Text = textBoxText.Text;
                listBoxInspectItems.Items.Clear();
                for (int i = 0; i < _matches.Count; i++)
                    listBoxInspectItems.Items.Add(_matches[i].Text);
                listBoxInspectItems.SelectedIndex = index;
                ShowCount();
                listBoxInspectItems_SelectedIndexChanged(null, null);
            }
        }
Esempio n. 12
0
        private void linkLabelPreview_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabelPreview.Enabled = false;
            Cursor = Cursors.WaitCursor;
            try
            {
                int width;
                int height;
                GetResolution(out width, out height);
                using (var bmp = new Bitmap(width, height))
                {
                    using (var g = Graphics.FromImage(bmp))
                    {
                        var p = _subtitle.Paragraphs[subtitleListView1.SelectedItems[0].Index];
                        FillPreviewBackground(bmp, g, p);

                        var nBmp = new NikseBitmap(pictureBox1.Image as Bitmap);
                        nBmp.CropSidesAndBottom(100, Color.Transparent, true);
                        using (var textBmp = nBmp.GetBitmap())
                        {
                            var bp = MakeMakeBitmapParameter(subtitleListView1.SelectedItems[0].Index, width, height);
                            var alignment = GetAlignmentFromParagraph(bp, _format, _subtitle);
                            if (comboBoxHAlign.Visible && alignment == ContentAlignment.BottomCenter && _format.GetType() != typeof(AdvancedSubStationAlpha) && _format.GetType() != typeof(SubStationAlpha))
                            {
                                if (comboBoxHAlign.SelectedIndex == 0)
                                {
                                    alignment = ContentAlignment.BottomLeft;
                                }
                                else if (comboBoxHAlign.SelectedIndex == 2)
                                {
                                    alignment = ContentAlignment.BottomRight;
                                }
                            }

                            int x = (bmp.Width - textBmp.Width) / 2;
                            if (alignment == ContentAlignment.BottomLeft || alignment == ContentAlignment.MiddleLeft || alignment == ContentAlignment.TopLeft)
                                x = int.Parse(comboBoxBottomMargin.Text);
                            else if (alignment == ContentAlignment.BottomRight || alignment == ContentAlignment.MiddleRight || alignment == ContentAlignment.TopRight)
                                x = bmp.Width - textBmp.Width - int.Parse(comboBoxBottomMargin.Text);

                            int y = bmp.Height - textBmp.Height - int.Parse(comboBoxBottomMargin.Text);
                            if (alignment == ContentAlignment.BottomLeft || alignment == ContentAlignment.MiddleLeft || alignment == ContentAlignment.TopLeft)
                                x = int.Parse(comboBoxBottomMargin.Text);
                            else if (alignment == ContentAlignment.BottomRight || alignment == ContentAlignment.MiddleRight || alignment == ContentAlignment.TopRight)
                                x = bmp.Width - textBmp.Width - int.Parse(comboBoxBottomMargin.Text);
                            if (alignment == ContentAlignment.MiddleLeft || alignment == ContentAlignment.MiddleCenter || alignment == ContentAlignment.MiddleRight)
                                y = (groupBoxExportImage.Height - 4 - textBmp.Height) / 2;
                            else if (alignment == ContentAlignment.TopLeft || alignment == ContentAlignment.TopCenter || alignment == ContentAlignment.TopRight)
                                y = int.Parse(comboBoxBottomMargin.Text);

                            g.DrawImageUnscaled(textBmp, new Point(x, y));
                        }
                    }

                    using (var form = new ExportPngXmlPreview(bmp))
                    {
                        Cursor = Cursors.Default;
                        form.ShowDialog(this);
                    }
                }
            }
            finally
            {
                Cursor = Cursors.Default;
                linkLabelPreview.Enabled = true;
            }
        }
Esempio n. 13
0
        private int WriteParagraph(int width, StringBuilder sb, int border, int height, int imagesSavedCount, VobSubWriter vobSubWriter, FileStream binarySubtitleFile, MakeBitmapParameter param, int i)
        {
            if (param.Bitmap != null)
            {
                if (_exportType == "BLURAYSUP")
                {
                    if (!param.Saved)
                    {
                        binarySubtitleFile.Write(param.Buffer, 0, param.Buffer.Length);
                    }
                    param.Saved = true;
                }
                else if (_exportType == "VOBSUB")
                {
                    if (!param.Saved)
                        vobSubWriter.WriteParagraph(param.P, param.Bitmap, param.Alignment);
                    param.Saved = true;
                }
                else if (_exportType == "FAB")
                {
                    if (!param.Saved)
                    {
                        string numberString = string.Format("IMAGE{0:000}", i);
                        string fileName = Path.Combine(folderBrowserDialog1.SelectedPath, numberString + "." + comboBoxImageFormat.Text.ToLower());

                        if (checkBoxFullFrameImage.Visible && checkBoxFullFrameImage.Checked)
                        {
                            var nbmp = new NikseBitmap(param.Bitmap);
                            nbmp.ReplaceTransparentWith(panelFullFrameBackground.BackColor);
                            using (var bmp = nbmp.GetBitmap())
                            {
                                // param.Bitmap.Save(fileName, ImageFormat);
                                imagesSavedCount++;

                                //RACE001.TIF 00;00;02;02 00;00;03;15 000 000 720 480
                                //RACE002.TIF 00;00;05;18 00;00;09;20 000 000 720 480
                                int top = param.ScreenHeight - (param.Bitmap.Height + param.BottomMargin);
                                int left = (param.ScreenWidth - param.Bitmap.Width) / 2;

                                var b = new NikseBitmap(param.ScreenWidth, param.ScreenHeight);
                                {
                                    b.Fill(panelFullFrameBackground.BackColor);
                                    using (var fullSize = b.GetBitmap())
                                    {
                                        if (param.Alignment == ContentAlignment.BottomLeft || param.Alignment == ContentAlignment.MiddleLeft || param.Alignment == ContentAlignment.TopLeft)
                                            left = param.LeftRightMargin;
                                        else if (param.Alignment == ContentAlignment.BottomRight || param.Alignment == ContentAlignment.MiddleRight || param.Alignment == ContentAlignment.TopRight)
                                            left = param.ScreenWidth - param.Bitmap.Width - param.LeftRightMargin;
                                        if (param.Alignment == ContentAlignment.TopLeft || param.Alignment == ContentAlignment.TopCenter || param.Alignment == ContentAlignment.TopRight)
                                            top = param.BottomMargin;
                                        if (param.Alignment == ContentAlignment.MiddleLeft || param.Alignment == ContentAlignment.MiddleCenter || param.Alignment == ContentAlignment.MiddleRight)
                                            top = param.ScreenHeight - (param.Bitmap.Height / 2);

                                        using (var g = Graphics.FromImage(fullSize))
                                        {
                                            g.DrawImage(bmp, left, top);
                                            g.Dispose();
                                        }
                                        SaveImage(fullSize, fileName, ImageFormat);
                                    }
                                }
                                left = 0;
                                top = 0;
                                sb.AppendLine(string.Format("{0} {1} {2} {3} {4} {5} {6}", Path.GetFileName(fileName), FormatFabTime(param.P.StartTime, param), FormatFabTime(param.P.EndTime, param), left, top, left + param.ScreenWidth, top + param.ScreenHeight));
                            }
                        }
                        else
                        {
                            SaveImage(param.Bitmap, fileName, ImageFormat);

                            imagesSavedCount++;

                            //RACE001.TIF 00;00;02;02 00;00;03;15 000 000 720 480
                            //RACE002.TIF 00;00;05;18 00;00;09;20 000 000 720 480
                            int top = param.ScreenHeight - (param.Bitmap.Height + param.BottomMargin);
                            int left = (param.ScreenWidth - param.Bitmap.Width) / 2;

                            if (param.Alignment == ContentAlignment.BottomLeft || param.Alignment == ContentAlignment.MiddleLeft || param.Alignment == ContentAlignment.TopLeft)
                                left = param.LeftRightMargin;
                            else if (param.Alignment == ContentAlignment.BottomRight || param.Alignment == ContentAlignment.MiddleRight || param.Alignment == ContentAlignment.TopRight)
                                left = param.ScreenWidth - param.Bitmap.Width - param.LeftRightMargin;
                            if (param.Alignment == ContentAlignment.TopLeft || param.Alignment == ContentAlignment.TopCenter || param.Alignment == ContentAlignment.TopRight)
                                top = param.BottomMargin;
                            if (param.Alignment == ContentAlignment.MiddleLeft || param.Alignment == ContentAlignment.MiddleCenter || param.Alignment == ContentAlignment.MiddleRight)
                                top = param.ScreenHeight - (param.Bitmap.Height / 2);
                            sb.AppendLine(string.Format("{0} {1} {2} {3} {4} {5} {6}", Path.GetFileName(fileName), FormatFabTime(param.P.StartTime, param), FormatFabTime(param.P.EndTime, param), left, top, left + param.Bitmap.Width, top + param.Bitmap.Height));
                        }
                        param.Saved = true;
                    }
                }
                else if (_exportType == "STL")
                {
                    if (!param.Saved)
                    {
                        string numberString = string.Format("IMAGE{0:000}", i);
                        string fileName = Path.Combine(folderBrowserDialog1.SelectedPath, numberString + "." + comboBoxImageFormat.Text.ToLower());
                        SaveImage(param.Bitmap, fileName, ImageFormat);

                        imagesSavedCount++;

                        const string paragraphWriteFormat = "{0} , {1} , {2}\r\n";
                        const string timeFormat = "{0:00}:{1:00}:{2:00}:{3:00}";

                        double factor = (TimeCode.BaseUnit / Configuration.Settings.General.CurrentFrameRate);
                        string startTime = string.Format(timeFormat, param.P.StartTime.Hours, param.P.StartTime.Minutes, param.P.StartTime.Seconds, (int)Math.Round(param.P.StartTime.Milliseconds / factor));
                        string endTime = string.Format(timeFormat, param.P.EndTime.Hours, param.P.EndTime.Minutes, param.P.EndTime.Seconds, (int)Math.Round(param.P.EndTime.Milliseconds / factor));
                        sb.AppendFormat(paragraphWriteFormat, startTime, endTime, fileName);

                        param.Saved = true;
                    }
                }
                else if (_exportType == "SPUMUX")
                {
                    if (!param.Saved)
                    {
                        string numberString = string.Format("IMAGE{0:000}", i);
                        string fileName = Path.Combine(folderBrowserDialog1.SelectedPath, numberString + "." + comboBoxImageFormat.Text.ToLower());

                        foreach (var encoder in ImageCodecInfo.GetImageEncoders())
                        {
                            if (encoder.FormatID == ImageFormat.Png.Guid)
                            {
                                var parameters = new EncoderParameters();
                                parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8);

                                var nbmp = new NikseBitmap(param.Bitmap);
                                var b = nbmp.ConverTo8BitsPerPixel();
                                b.Save(fileName, encoder, parameters);
                                b.Dispose();

                                break;
                            }
                        }
                        imagesSavedCount++;

                        const string paragraphWriteFormat = "\t\t<spu start=\"{0}\" end=\"{1}\" image=\"{2}\"  />";
                        const string timeFormat = "{0:00}:{1:00}:{2:00}:{3:00}";

                        double factor = (TimeCode.BaseUnit / Configuration.Settings.General.CurrentFrameRate);
                        string startTime = string.Format(timeFormat, param.P.StartTime.Hours, param.P.StartTime.Minutes, param.P.StartTime.Seconds, (int)Math.Round(param.P.StartTime.Milliseconds / factor));
                        string endTime = string.Format(timeFormat, param.P.EndTime.Hours, param.P.EndTime.Minutes, param.P.EndTime.Seconds, (int)Math.Round(param.P.EndTime.Milliseconds / factor));
                        sb.AppendLine(string.Format(paragraphWriteFormat, startTime, endTime, fileName));

                        param.Saved = true;
                    }
                }
                else if (_exportType == "FCP")
                {
                    if (!param.Saved)
                    {
                        string numberString = string.Format(Path.GetFileNameWithoutExtension(Path.GetFileName(param.SavDialogFileName)) + "{0:0000}", i);
                        string fileName = numberString + "." + comboBoxImageFormat.Text.ToLower();
                        string fileNameNoPath = Path.GetFileName(fileName);
                        string fileNameNoExt = Path.GetFileNameWithoutExtension(fileNameNoPath);
                        string template = " <clipitem id=\"" + System.Security.SecurityElement.Escape(fileNameNoPath) + "\">" + Environment.NewLine +

            //              <pathurl>file://localhost/" + fileNameNoPath.Replace(" ", "%20") + @"</pathurl>

                                          @"            <name>" + System.Security.SecurityElement.Escape(fileNameNoPath) + @"</name>
            <duration>[DURATION]</duration>
            <rate>
              <ntsc>FALSE</ntsc>
              <timebase>25</timebase>
            </rate>
            <in>[IN]</in>
            <out>[OUT]</out>
            <start>[START]</start>
            <end>[END]</end>
            <pixelaspectratio>" + param.VideoResolution + @"</pixelaspectratio>
            <stillframe>TRUE</stillframe>
            <anamorphic>FALSE</anamorphic>
            <alphatype>straight</alphatype>
            <masterclipid>" + System.Security.SecurityElement.Escape(fileNameNoPath) + @"1</masterclipid>" + Environment.NewLine +
                                          "           <file id=\"" + fileNameNoExt + "\">" + @"
              <name>" + System.Security.SecurityElement.Escape(fileNameNoPath) + @"</name>
              <pathurl>" + Utilities.UrlEncode(fileNameNoPath) + @"</pathurl>
              <rate>
                <timebase>25</timebase>
              </rate>
              <duration>[DURATION]</duration>
              <width>" + param.ScreenWidth + @"</width>
              <height>" + param.ScreenHeight + @"</height>
              <media>
                <video>
                  <duration>[DURATION]</duration>
                  <stillframe>TRUE</stillframe>
                  <samplecharacteristics>
                    <width>" + param.ScreenWidth + @"</width>
                    <height>" + param.ScreenHeight + @"</height>
                  </samplecharacteristics>
                </video>
              </media>
            </file>
            <sourcetrack>
              <mediatype>video</mediatype>
            </sourcetrack>
            <fielddominance>none</fielddominance>
              </clipitem>";

                        fileName = Path.Combine(Path.GetDirectoryName(param.SavDialogFileName), fileName);

                        if (comboBoxImageFormat.Text == "8-bit png")
                        {
                            foreach (var encoder in ImageCodecInfo.GetImageEncoders())
                            {
                                if (encoder.FormatID == ImageFormat.Png.Guid)
                                {
                                    var parameters = new EncoderParameters();
                                    parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8);

                                    var nbmp = new NikseBitmap(param.Bitmap);
                                    var b = nbmp.ConverTo8BitsPerPixel();
                                    b.Save(fileName, encoder, parameters);
                                    b.Dispose();

                                    break;
                                }
                            }
                        }
                        else
                        {
                            SaveImage(param.Bitmap, fileName, ImageFormat);
                        }
                        imagesSavedCount++;

                        int duration = (int)Math.Round(param.P.Duration.TotalSeconds * param.FramesPerSeconds);
                        int start = (int)Math.Round(param.P.StartTime.TotalSeconds * param.FramesPerSeconds);
                        int end = (int)Math.Round(param.P.EndTime.TotalSeconds * param.FramesPerSeconds);

                        template = template.Replace("[DURATION]", duration.ToString(CultureInfo.InvariantCulture));
                        template = template.Replace("[IN]", start.ToString(CultureInfo.InvariantCulture));
                        template = template.Replace("[OUT]", end.ToString(CultureInfo.InvariantCulture));
                        template = template.Replace("[START]", start.ToString(CultureInfo.InvariantCulture));
                        template = template.Replace("[END]", end.ToString(CultureInfo.InvariantCulture));
                        sb.AppendLine(template);

                        param.Saved = true;
                    }
                }
                else if (_exportType == "DOST")
                {
                    if (!param.Saved)
                    {
                        string numberString = string.Format("{0:0000}", i);
                        string fileName = Path.Combine(Path.GetDirectoryName(saveFileDialog1.FileName), Path.GetFileNameWithoutExtension(saveFileDialog1.FileName).Replace(" ", "_")) + "_" + numberString + ".png";

                        foreach (var encoder in ImageCodecInfo.GetImageEncoders())
                        {
                            if (encoder.FormatID == ImageFormat.Png.Guid)
                            {
                                var parameters = new EncoderParameters();
                                parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8);

                                var nbmp = new NikseBitmap(param.Bitmap);
                                var b = nbmp.ConverTo8BitsPerPixel();
                                b.Save(fileName, encoder, parameters);
                                b.Dispose();

                                break;
                            }
                        }
                        imagesSavedCount++;

                        const string paragraphWriteFormat = "{0}\t{1}\t{2}\t{4}\t{5}\t{3}\t0\t0";

                        int top = param.ScreenHeight - (param.Bitmap.Height + param.BottomMargin);
                        int left = (param.ScreenWidth - param.Bitmap.Width) / 2;
                        if (param.Alignment == ContentAlignment.BottomLeft || param.Alignment == ContentAlignment.MiddleLeft || param.Alignment == ContentAlignment.TopLeft)
                            left = param.LeftRightMargin;
                        else if (param.Alignment == ContentAlignment.BottomRight || param.Alignment == ContentAlignment.MiddleRight || param.Alignment == ContentAlignment.TopRight)
                            left = param.ScreenWidth - param.Bitmap.Width - param.LeftRightMargin;
                        if (param.Alignment == ContentAlignment.TopLeft || param.Alignment == ContentAlignment.TopCenter || param.Alignment == ContentAlignment.TopRight)
                            top = param.BottomMargin;
                        if (param.Alignment == ContentAlignment.MiddleLeft || param.Alignment == ContentAlignment.MiddleCenter || param.Alignment == ContentAlignment.MiddleRight)
                            top = param.ScreenHeight - (param.Bitmap.Height / 2);

                        string startTime = ToHHMMSSFF(param.P.StartTime);
                        string endTime = ToHHMMSSFF(param.P.EndTime);
                        sb.AppendLine(string.Format(paragraphWriteFormat, numberString, startTime, endTime, Path.GetFileName(fileName), left, top));

                        param.Saved = true;
                    }
                }
                else if (_exportType == "IMAGE/FRAME")
                {
                    if (!param.Saved)
                    {
                        var imageFormat = ImageFormat;

                        int lastFrame = imagesSavedCount;
                        int startFrame = (int)Math.Round(param.P.StartTime.TotalMilliseconds / (TimeCode.BaseUnit / param.FramesPerSeconds));
                        var empty = new Bitmap(param.ScreenWidth, param.ScreenHeight);

                        if (imagesSavedCount == 0 && checkBoxSkipEmptyFrameAtStart.Checked)
                        {
                        }
                        else
                        {
                            // Save empty picture for each frame up to start frame
                            for (int k = lastFrame + 1; k < startFrame; k++)
                            {
                                string numberString = string.Format("{0:00000}", k);
                                string fileName = Path.Combine(folderBrowserDialog1.SelectedPath, numberString + "." + comboBoxImageFormat.Text.ToLower());
                                empty.Save(fileName, imageFormat);
                                imagesSavedCount++;
                            }
                        }

                        int endFrame = (int)Math.Round(param.P.EndTime.TotalMilliseconds / (TimeCode.BaseUnit / param.FramesPerSeconds));
                        var fullSize = new Bitmap(param.ScreenWidth, param.ScreenHeight);
                        Graphics g = Graphics.FromImage(fullSize);
                        g.DrawImage(param.Bitmap, (param.ScreenWidth - param.Bitmap.Width) / 2, param.ScreenHeight - (param.Bitmap.Height + param.BottomMargin));
                        g.Dispose();

                        if (imagesSavedCount > startFrame)
                            startFrame = imagesSavedCount; // no overlapping

                        // Save sub picture for each frame in duration
                        for (int k = startFrame; k <= endFrame; k++)
                        {
                            string numberString = string.Format("{0:00000}", k);
                            string fileName = Path.Combine(folderBrowserDialog1.SelectedPath, numberString + "." + comboBoxImageFormat.Text.ToLower());
                            fullSize.Save(fileName, imageFormat);
                            imagesSavedCount++;
                        }
                        fullSize.Dispose();
                        param.Saved = true;
                    }
                }
                else if (_exportType == "DCINEMA_INTEROP")
                {
                    if (!param.Saved)
                    {
                        string numberString = string.Format("{0:0000}", i);
                        string fileName = Path.Combine(Path.GetDirectoryName(saveFileDialog1.FileName), numberString + ".png");
                        param.Bitmap.Save(fileName, ImageFormat.Png);
                        imagesSavedCount++;
                        param.Saved = true;
                        sb.AppendLine("<Subtitle FadeDownTime=\"" + 0 + "\" FadeUpTime=\"" + 0 + "\" TimeOut=\"" + DCSubtitle.ConvertToTimeString(param.P.EndTime) + "\" TimeIn=\"" + DCSubtitle.ConvertToTimeString(param.P.StartTime) + "\" SpotNumber=\"" + param.P.Number + "\">");
                        if (param.Depth3D == 0)
                            sb.AppendLine("<Image VPosition=\"9.7\" VAlign=\"bottom\" HAlign=\"center\">" + numberString + ".png" + "</Image>");
                        else
                            sb.AppendLine("<Image VPosition=\"9.7\" ZPosition=\"" + param.Depth3D + "\" VAlign=\"bottom\" HAlign=\"center\">" + numberString + ".png" + "</Image>");
                        sb.AppendLine("</Subtitle>");
                    }
                }
                else if (_exportType == "EDL")
                {
                    if (!param.Saved)
                    {
                        // 001  7M6C7986 V     C        14:14:55:21 14:15:16:24 01:00:10:18 01:00:31:21
                        var fileName1 = "IMG" + i.ToString(CultureInfo.InvariantCulture).PadLeft(5, '0');

                        var fullSize = new Bitmap(param.ScreenWidth, param.ScreenHeight);
                        using (var g = Graphics.FromImage(fullSize))
                        {
                            g.DrawImage(param.Bitmap, (param.ScreenWidth - param.Bitmap.Width) / 2, param.ScreenHeight - (param.Bitmap.Height + param.BottomMargin));
                        }
                        var fileName2 = Path.Combine(Path.GetDirectoryName(param.SavDialogFileName), fileName1 + ".PNG");
                        fullSize.Save(fileName2, ImageFormat.Png);
                        fullSize.Dispose();

                        string line = string.Format("{0:000}  {1}  V     C        {2} {3} {4} {5}", i, fileName1, new TimeCode(0).ToHHMMSSFF(), param.P.Duration.ToHHMMSSFF(), param.P.StartTime.ToHHMMSSFF(), param.P.EndTime.ToHHMMSSFF());
                        sb.AppendLine(line);
                        sb.AppendLine();

                        imagesSavedCount++;
                        param.Saved = true;
                    }
                }
                else // BDNXML
                {
                    if (!param.Saved)
                    {
                        string numberString = string.Format("{0:0000}", i);
                        string fileName = Path.Combine(folderBrowserDialog1.SelectedPath, numberString + ".png");

                        if (comboBoxImageFormat.Text == "Png 8-bit")
                        {
                            foreach (var encoder in ImageCodecInfo.GetImageEncoders())
                            {
                                if (encoder.FormatID == ImageFormat.Png.Guid)
                                {
                                    var parameters = new EncoderParameters();
                                    parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8);

                                    var nbmp = new NikseBitmap(param.Bitmap);
                                    var b = nbmp.ConverTo8BitsPerPixel();
                                    b.Save(fileName, encoder, parameters);
                                    b.Dispose();

                                    break;
                                }
                            }
                        }
                        else
                        {
                            param.Bitmap.Save(fileName, ImageFormat.Png);
                        }

                        imagesSavedCount++;

                        //<Event InTC="00:00:24:07" OutTC="00:00:31:13" Forced="False">
                        //  <Graphic Width="696" Height="111" X="612" Y="930">subtitle_exp_0001.png</Graphic>
                        //</Event>
                        sb.AppendLine("<Event InTC=\"" + ToHHMMSSFF(param.P.StartTime) + "\" OutTC=\"" +
                                      ToHHMMSSFF(param.P.EndTime) + "\" Forced=\"" + param.Forced.ToString().ToLower() + "\">");

                        int x = (width - param.Bitmap.Width) / 2;
                        int y = height - (param.Bitmap.Height + param.BottomMargin);
                        switch (param.Alignment)
                        {
                            case ContentAlignment.BottomLeft:
                                x = border;
                                y = height - (param.Bitmap.Height + param.BottomMargin);
                                break;
                            case ContentAlignment.BottomRight:
                                x = height - param.Bitmap.Width - border;
                                y = height - (param.Bitmap.Height + param.BottomMargin);
                                break;
                            case ContentAlignment.MiddleCenter:
                                x = (width - param.Bitmap.Width) / 2;
                                y = (height - param.Bitmap.Height) / 2;
                                break;
                            case ContentAlignment.MiddleLeft:
                                x = border;
                                y = (height - param.Bitmap.Height) / 2;
                                break;
                            case ContentAlignment.MiddleRight:
                                x = width - param.Bitmap.Width - border;
                                y = (height - param.Bitmap.Height) / 2;
                                break;
                            case ContentAlignment.TopCenter:
                                x = (width - param.Bitmap.Width) / 2;
                                y = border;
                                break;
                            case ContentAlignment.TopLeft:
                                x = border;
                                y = border;
                                break;
                            case ContentAlignment.TopRight:
                                x = width - param.Bitmap.Width - border;
                                y = border;
                                break;
                        }

                        sb.AppendLine("  <Graphic Width=\"" + param.Bitmap.Width.ToString(CultureInfo.InvariantCulture) + "\" Height=\"" +
                                      param.Bitmap.Height.ToString(CultureInfo.InvariantCulture) + "\" X=\"" + x.ToString(CultureInfo.InvariantCulture) + "\" Y=\"" + y.ToString(CultureInfo.InvariantCulture) +
                                      "\">" + numberString + ".png</Graphic>");
                        sb.AppendLine("</Event>");
                        param.Saved = true;
                    }
                }
            }
            return imagesSavedCount;
        }
Esempio n. 14
0
        public Bitmap ToOldBitmap()
        {
            if (ExpandedList != null && ExpandedList.Count > 0)
            {
                int minX = X;
                int minY = Y;
                int maxX = X + Width;
                int maxY = Y + Height;
                var list = new List<BinaryOcrBitmap>();
                list.Add(this);
                foreach (BinaryOcrBitmap bob in ExpandedList)
                {
                    if (bob.X < minX)
                        minX = bob.X;
                    if (bob.Y < minY)
                        minY = bob.Y;
                    if (bob.X + bob.Width > maxX)
                        maxX = bob.X + bob.Width;
                    if (bob.Y + bob.Height > maxY)
                        maxY = bob.Y + bob.Height;
                    list.Add(bob);
                }
                var nbmp = new BinaryOcrBitmap(maxX - minX, maxY - minY);
                foreach (BinaryOcrBitmap bob in list)
                {
                    for (int y = 0; y < bob.Height; y++)
                    {
                        for (int x = 0; x < bob.Width; x++)
                        {
                            int c = bob.GetPixel(x, y);
                            if (c > 0)
                                nbmp.SetPixel(bob.X - minX + x, bob.Y - minY + y, 1);
                        }
                    }
                }

                return nbmp.ToOldBitmap(); // Resursive
            }
            else
            {
                var nbmp = new NikseBitmap(Width, Height);
                for (int y = 0; y < Height; y++)
                {
                    for (int x = 0; x < Width; x++)
                    {
                        Color c = Color.Transparent;
                        if (GetPixel(x, y) > 0)
                            c = Color.White;
                        nbmp.SetPixel(x, y, c);
                    }
                }
                return nbmp.GetBitmap();
            }
        }
Esempio n. 15
0
        private Bitmap GenerateImageFromTextWithStyle(string text)
        {
            const bool subtitleFontBold = false;
            bool subtitleAlignLeft = comboBoxHAlign.SelectedIndex == 0;

            // remove styles for display text (except italic)
            text = RemoveSubStationAlphaFormatting(text);
            text = text.Replace("<b>", string.Empty);
            text = text.Replace("</b>", string.Empty);
            text = text.Replace("<B>", string.Empty);
            text = text.Replace("</B>", string.Empty);
            text = text.Replace("<u>", string.Empty);
            text = text.Replace("</u>", string.Empty);
            text = text.Replace("<U>", string.Empty);
            text = text.Replace("</U>", string.Empty);

            Font font;
            try
            {
                font = new Font(_subtitleFontName, _subtitleFontSize, FontStyle.Regular);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                font = new Font(FontFamily.Families[0].Name, _subtitleFontSize);
            }
            var bmp = new Bitmap(400, 200);
            var g = Graphics.FromImage(bmp);

            SizeF textSize = g.MeasureString("Hj!", font);
            var lineHeight = (textSize.Height * 0.64f);

            textSize = g.MeasureString(HtmlUtil.RemoveHtmlTags(text), font);
            g.Dispose();
            bmp.Dispose();
            int sizeX = (int)(textSize.Width * 0.8) + 40;
            int sizeY = (int)(textSize.Height * 0.8) + 30;
            if (sizeX < 1)
                sizeX = 1;
            if (sizeY < 1)
                sizeY = 1;
            bmp = new Bitmap(sizeX, sizeY);
            g = Graphics.FromImage(bmp);

            var lefts = new List<float>();
            foreach (var line in HtmlUtil.RemoveOpenCloseTags(text, HtmlUtil.TagItalic, HtmlUtil.TagFont).SplitToLines())
            {
                if (subtitleAlignLeft)
                    lefts.Add(5);
                else
                    lefts.Add((float)(bmp.Width - g.MeasureString(line, font).Width * 0.8 + 15) / 2);
            }

            g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.CompositingQuality = CompositingQuality.HighQuality;

            var sf = new StringFormat();
            sf.Alignment = StringAlignment.Near;
            sf.LineAlignment = StringAlignment.Near;// draw the text to a path
            var path = new GraphicsPath();

            // display italic
            var sb = new StringBuilder();
            int i = 0;
            bool isItalic = false;
            float left = 5;
            if (lefts.Count > 0)
                left = lefts[0];
            float top = 5;
            bool newLine = false;
            int lineNumber = 0;
            float leftMargin = left;
            bool italicFromStart = false;
            int newLinePathPoint = -1;
            Color c = _subtitleColor;
            var colorStack = new Stack<Color>();
            var lastText = new StringBuilder();
            while (i < text.Length)
            {
                if (text.Substring(i).StartsWith("<font ", StringComparison.OrdinalIgnoreCase))
                {
                    float addLeft = 0;
                    int oldPathPointIndex = path.PointCount;
                    if (oldPathPointIndex < 0)
                        oldPathPointIndex = 0;

                    if (sb.Length > 0)
                    {
                        TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    if (path.PointCount > 0)
                    {
                        PointF[] list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                        for (int k = oldPathPointIndex; k < list.Length; k++)
                        {
                            if (list[k].X > addLeft)
                                addLeft = list[k].X;
                        }
                    }
                    if (addLeft == 0)
                        addLeft = left + 2;
                    left = addLeft;

                    if (_borderWidth > 0)
                        g.DrawPath(new Pen(_borderColor, _borderWidth), path);
                    g.FillPath(new SolidBrush(c), path);
                    path.Reset();
                    path = new GraphicsPath();
                    sb = new StringBuilder();

                    int endIndex = text.Substring(i).IndexOf('>');
                    if (endIndex < 0)
                    {
                        i += 9999;
                    }
                    else
                    {
                        string fontContent = text.Substring(i, endIndex);
                        if (fontContent.Contains(" color="))
                        {
                            var arr = fontContent.Substring(fontContent.IndexOf(" color=", StringComparison.Ordinal) + 7).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (arr.Length > 0)
                            {
                                string fontColor = arr[0].Trim('\'').Trim('"').Trim('\'');
                                try
                                {
                                    colorStack.Push(c); // save old color
                                    if (fontColor.StartsWith("rgb("))
                                    {
                                        arr = fontColor.Remove(0, 4).TrimEnd(')').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                        c = Color.FromArgb(int.Parse(arr[0]), int.Parse(arr[1]), int.Parse(arr[2]));
                                    }
                                    else
                                    {
                                        c = ColorTranslator.FromHtml(fontColor);
                                    }
                                }
                                catch
                                {
                                    c = _subtitleColor;
                                }
                            }
                        }
                        i += endIndex;
                    }
                }
                else if (text.Substring(i).StartsWith("</font>", StringComparison.OrdinalIgnoreCase))
                {
                    if (text.Substring(i).ToLower().Replace("</font>", string.Empty).Length > 0)
                    {
                        if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                        {
                            string t = sb.ToString();
                            sb.Clear();
                            sb.Append(' ');
                            sb.Append(t);
                        }

                        float addLeft = 0;
                        int oldPathPointIndex = path.PointCount - 1;
                        if (oldPathPointIndex < 0)
                            oldPathPointIndex = 0;
                        if (sb.Length > 0)
                        {
                            TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                        }
                        if (path.PointCount > 0)
                        {
                            PointF[] list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                            for (int k = oldPathPointIndex; k < list.Length; k++)
                            {
                                if (list[k].X > addLeft)
                                    addLeft = list[k].X;
                            }
                        }
                        if (addLeft == 0)
                            addLeft = left + 2;
                        left = addLeft;

                        if (_borderWidth > 0)
                            g.DrawPath(new Pen(_borderColor, _borderWidth), path);
                        g.FillPath(new SolidBrush(c), path);
                        path.Reset();
                        //path = new GraphicsPath();
                        sb = new StringBuilder();
                        if (colorStack.Count > 0)
                            c = colorStack.Pop();
                    }
                    i += 6;
                }
                else if (text.Substring(i).StartsWith("<i>", StringComparison.OrdinalIgnoreCase))
                {
                    italicFromStart = i == 0;
                    if (sb.Length > 0)
                    {
                        TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    isItalic = true;
                    i += 2;
                }
                else if (text.Substring(i).StartsWith("</i>", StringComparison.OrdinalIgnoreCase) && isItalic)
                {
                    if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                    {
                        string t = sb.ToString();
                        sb.Clear();
                        sb.Append(' ');
                        sb.Append(t);
                    }
                    TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    isItalic = false;
                    i += 3;
                }
                else if (text.Substring(i).StartsWith(Environment.NewLine))
                {
                    TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);

                    top += lineHeight;
                    newLine = true;
                    i += Environment.NewLine.Length - 1;
                    lineNumber++;
                    if (lineNumber < lefts.Count)
                    {
                        leftMargin = lefts[lineNumber];
                        left = leftMargin;
                    }
                    if (isItalic)
                        italicFromStart = true;
                }
                else
                {
                    sb.Append(text[i]);
                }
                i++;
            }
            if (sb.Length > 0)
                TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
            sf.Dispose();

            if (_borderWidth > 0)
                g.DrawPath(new Pen(_borderColor, _borderWidth), path);
            g.FillPath(new SolidBrush(c), path);
            g.Dispose();
            var nbmp = new NikseBitmap(bmp);
            nbmp.CropTransparentSidesAndBottom(2, true);
            return nbmp.GetBitmap();
        }
Esempio n. 16
0
        private static bool IsMatchPointForeGround(NOcrPoint op, bool loose, NikseBitmap nbmp, NOcrChar nOcrChar)
        {
            if (Math.Abs(op.Start.X - op.End.X) < 2 && Math.Abs(op.End.Y - op.Start.Y) < 2)
                return false;

            foreach (Point point in op.ScaledGetPoints(nOcrChar, nbmp.Width, nbmp.Height))
            {
                if (point.X >= 0 && point.Y >= 0 && point.X < nbmp.Width && point.Y < nbmp.Height)
                {
                    Color c = nbmp.GetPixel(point.X, point.Y);
                    if (c.A > 150 && c.R + 100 + c.G + c.B > VobSubOcr.NocrMinColor)
                    {
                    }
                    else
                    {
                        return false;
                    }

                    if (loose)
                    {
                        if (nbmp.Width > 10 && point.X + 1 < nbmp.Width)
                        {
                            c = nbmp.GetPixel(point.X + 1, point.Y);
                            if (c.A > 150 && c.R + 100 + c.G + c.B > VobSubOcr.NocrMinColor)
                            {
                            }
                            else
                            {
                                return false;
                            }
                        }

                        if (nbmp.Width > 10 && point.X >= 1)
                        {
                            c = nbmp.GetPixel(point.X - 1, point.Y);
                            if (c.A > 150 && c.R + 100 + c.G + c.B > VobSubOcr.NocrMinColor)
                            {
                            }
                            else
                            {
                                return false;
                            }
                        }

                        if (nbmp.Height > 10 && point.Y + 1 < nbmp.Height)
                        {
                            c = nbmp.GetPixel(point.X, point.Y + 1);
                            if (c.A > 150 && c.R + 100 + c.G + c.B > VobSubOcr.NocrMinColor)
                            {
                            }
                            else
                            {
                                return false;
                            }
                        }

                        if (nbmp.Height > 10 && point.Y >= 1)
                        {
                            c = nbmp.GetPixel(point.X, point.Y - 1);
                            if (c.A > 150 && c.R + 100 + c.G + c.B > VobSubOcr.NocrMinColor)
                            {
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
            }
            return true;
        }
Esempio n. 17
0
        public static void GenerateLineSegments(int numberOfLines, bool veryPrecise, NOcrChar nOcrChar, NikseBitmap nbmp)
        {
            const int giveUpCount = 10000;
            var r = new Random();
            int count = 0;
            int hits = 0;
            bool tempVeryPrecise = veryPrecise;
            while (hits < numberOfLines && count < giveUpCount)
            {
                var start = new Point(r.Next(nOcrChar.Width), r.Next(nOcrChar.Height));
                var end = new Point(r.Next(nOcrChar.Width), r.Next(nOcrChar.Height));

                if (hits < 5 && count < 100) // a few large lines
                {
                    for (int k = 0; k < 500; k++)
                    {
                        if (Math.Abs(start.X - end.X) + Math.Abs(start.Y - end.Y) > nOcrChar.Height / 2)
                        {
                            break;
                        }
                        else
                        {
                            end = new Point(r.Next(nOcrChar.Width), r.Next(nOcrChar.Height));
                        }
                    }
                }
                else // and a lot of small lines
                {
                    for (int k = 0; k < 500; k++)
                    {
                        if (Math.Abs(start.X - end.X) + Math.Abs(start.Y - end.Y) < 5)
                        {
                            break;
                        }
                        else
                        {
                            end = new Point(r.Next(nOcrChar.Width), r.Next(nOcrChar.Height));
                        }
                    }
                }

                var op = new NOcrPoint(start, end);
                bool ok = true;
                foreach (NOcrPoint existingOp in nOcrChar.LinesForeground)
                {
                    if (existingOp.Start.X == op.Start.X && existingOp.Start.Y == op.Start.Y &&
                        existingOp.End.X == op.End.X && existingOp.End.Y == op.End.Y)
                        ok = false;
                }
                if (ok && IsMatchPointForeGround(op, !tempVeryPrecise, nbmp, nOcrChar))
                {
                    nOcrChar.LinesForeground.Add(op);
                    //AddHistoryItem(nOcrChar);
                    hits++;
                }
                count++;
                if (count > giveUpCount - 100 && !tempVeryPrecise)
                    tempVeryPrecise = true;
            }

            count = 0;
            hits = 0;
            tempVeryPrecise = veryPrecise;
            while (hits < numberOfLines && count < giveUpCount)
            {
                var start = new Point(r.Next(nOcrChar.Width), r.Next(nOcrChar.Height));
                var end = new Point(r.Next(nOcrChar.Width), r.Next(nOcrChar.Height));

                if (hits < 5 && count < 100) // a few large lines
                {
                    for (int k = 0; k < 500; k++)
                    {
                        if (Math.Abs(start.X - end.X) + Math.Abs(start.Y - end.Y) > nOcrChar.Height / 2)
                        {
                            break;
                        }
                        else
                        {
                            end = new Point(r.Next(nOcrChar.Width), r.Next(nOcrChar.Height));
                        }
                    }
                }
                else // and a lot of small lines
                {
                    for (int k = 0; k < 500; k++)
                    {
                        if (Math.Abs(start.X - end.X) + Math.Abs(start.Y - end.Y) < 5)
                        {
                            break;
                        }
                        else
                        {
                            end = new Point(r.Next(nOcrChar.Width), r.Next(nOcrChar.Height));
                        }
                    }
                }

                var op = new NOcrPoint(start, end);
                bool ok = true;
                foreach (NOcrPoint existingOp in nOcrChar.LinesBackground)
                {
                    if (existingOp.Start.X == op.Start.X && existingOp.Start.Y == op.Start.Y &&
                        existingOp.End.X == op.End.X && existingOp.End.Y == op.End.Y)
                        ok = false;
                }
                if (ok && IsMatchPointBackGround(op, !tempVeryPrecise, nbmp, nOcrChar))
                {
                    nOcrChar.LinesBackground.Add(op);
                    //AddHistoryItem(nOcrChar);
                    hits++;
                }
                count++;

                if (count > giveUpCount - 100 && !tempVeryPrecise)
                    tempVeryPrecise = true;
            }
        }
Esempio n. 18
0
        internal void Initialize(Bitmap vobSubImage, ImageSplitterItem character, Point position, bool italicChecked, bool showShrink)
        {
            listBoxLinesForeground.Items.Clear();
            listBoxlinesBackground.Items.Clear();
            NikseBitmap nbmp = new NikseBitmap(vobSubImage);
            nbmp.ReplaceTransparentWith(Color.Black);
            vobSubImage = nbmp.GetBitmap();

            radioButtonHot.Checked = true;
            ShrinkSelection = false;
            ExpandSelection = false;

            textBoxCharacters.Text = string.Empty;
            _nocrChar = new NOcrChar();
            _nocrChar.MarginTop = character.Y - character.ParentY;
            _imageWidth = character.NikseBitmap.Width;
            _imageHeight = character.NikseBitmap.Height;
            _drawLineOn = false;
            _warningNoNotForegroundLinesShown = false;

            buttonShrinkSelection.Visible = showShrink;

            if (position.X != -1 && position.Y != -1)
            {
                StartPosition = FormStartPosition.Manual;
                Left = position.X;
                Top = position.Y;
            }

            pictureBoxSubtitleImage.Image = vobSubImage;
            pictureBoxCharacter.Image = character.NikseBitmap.GetBitmap();

            Bitmap org = (Bitmap)vobSubImage.Clone();
            Bitmap bm = new Bitmap(org.Width, org.Height);
            Graphics g = Graphics.FromImage(bm);
            g.DrawImage(org, 0, 0, org.Width, org.Height);
            g.DrawRectangle(Pens.Red, character.X, character.Y, character.NikseBitmap.Width, character.NikseBitmap.Height - 1);
            g.Dispose();
            pictureBoxSubtitleImage.Image = bm;

            pictureBoxCharacter.Top = labelCharacters.Top + 16;
            SizePictureBox();
            checkBoxItalic.Checked = italicChecked;

            _history = new List<NOcrChar>();
            _historyIndex = -1;

            _nocrChar.Width = _imageWidth;
            _nocrChar.Height = _imageHeight;
            GenerateLineSegments(150, false, _nocrChar, new NikseBitmap(pictureBoxCharacter.Image as Bitmap));
            ShowOcrPoints();
            pictureBoxCharacter.Invalidate();
        }
Esempio n. 19
0
 private void InitializeViaNikseBmp(NikseBitmap nbmp)
 {
     Width = nbmp.Width;
     Height = nbmp.Height;
     _colors = new byte[Width * Height];
     for (int y = 0; y < Height; y++)
     {
         for (int x = 0; x < Width; x++)
         {
             SetPixelViaAlpha(x, y, nbmp.GetAlpha(x, y));
         }
     }
     Hash = MurMurHash3.Hash(_colors);
     CalcuateNumberOfColoredPixels();
 }
Esempio n. 20
0
 public Bitmap ToOldBitmap()
 {
     var nbmp = new NikseBitmap(Width, Height);
     for (int y = 0; y < Height; y++)
     {
         for (int x = 0; x < Width; x++)
         {
             nbmp.SetPixel(x, y, this.GetPixel(x, y));
         }
     }
     return nbmp.GetBitmap();
 }
Esempio n. 21
0
        private Bitmap GenerateImageFromTextWithStyle(Paragraph p, out MakeBitmapParameter mbp)
        {
            mbp = new MakeBitmapParameter();
            mbp.P = p;

            if (_vobSubOcr != null)
            {
                var index = _subtitle.GetIndex(p);
                if (index >= 0)
                    return _vobSubOcr.GetSubtitleBitmap(index);
            }

            mbp.AlignLeft = comboBoxHAlign.SelectedIndex == 0;
            mbp.AlignRight = comboBoxHAlign.SelectedIndex == 2;
            mbp.SimpleRendering = checkBoxSimpleRender.Checked;
            mbp.BorderWidth = _borderWidth;
            mbp.BorderColor = _borderColor;
            mbp.SubtitleFontName = _subtitleFontName;
            mbp.SubtitleColor = _subtitleColor;
            mbp.SubtitleFontSize = _subtitleFontSize;
            mbp.SubtitleFontBold = _subtitleFontBold;
            mbp.LineHeight = (int)numericUpDownLineSpacing.Value;
            mbp.FullFrame = checkBoxFullFrameImage.Checked;
            mbp.FullFrameBackgroundcolor = panelFullFrameBackground.BackColor;

            if (_format.HasStyleSupport && !string.IsNullOrEmpty(p.Extra))
            {
                if (_format.GetType() == typeof(SubStationAlpha))
                {
                    var style = AdvancedSubStationAlpha.GetSsaStyle(p.Extra, _subtitle.Header);
                    mbp.SubtitleColor = style.Primary;
                    mbp.SubtitleFontBold = style.Bold;
                    mbp.SubtitleFontSize = style.FontSize;
                    if (style.BorderStyle == "3")
                    {
                        mbp.BackgroundColor = style.Background;
                    }
                }
                else if (_format.GetType() == typeof(AdvancedSubStationAlpha))
                {
                    var style = AdvancedSubStationAlpha.GetSsaStyle(p.Extra, _subtitle.Header);
                    mbp.SubtitleColor = style.Primary;
                    mbp.SubtitleFontBold = style.Bold;
                    mbp.SubtitleFontSize = style.FontSize;
                    if (style.BorderStyle == "3")
                    {
                        mbp.BackgroundColor = style.Outline;
                    }
                }
            }

            if (comboBoxBorderWidth.SelectedItem.ToString() == Configuration.Settings.Language.ExportPngXml.BorderStyleBoxForEachLine)
            {
                _borderWidth = 0;
                mbp.BackgroundColor = panelBorderColor.BackColor;
                mbp.BoxSingleLine = true;
            }
            else if (comboBoxBorderWidth.SelectedItem.ToString() == Configuration.Settings.Language.ExportPngXml.BorderStyleOneBox)
            {
                mbp.BoxSingleLine = false;
                _borderWidth = 0;
                mbp.BackgroundColor = panelBorderColor.BackColor;
            }

            int width;
            int height;
            GetResolution(out width, out height);
            mbp.ScreenWidth = width;
            mbp.ScreenHeight = height;
            mbp.VideoResolution = comboBoxResolution.Text;
            mbp.Type3D = comboBox3D.SelectedIndex;
            mbp.Depth3D = (int)numericUpDownDepth3D.Value;
            mbp.BottomMargin = comboBoxBottomMargin.SelectedIndex;
            mbp.ShadowWidth = comboBoxShadowWidth.SelectedIndex;
            mbp.ShadowAlpha = (int)numericUpDownShadowTransparency.Value;
            mbp.ShadowColor = panelShadowColor.BackColor;
            mbp.LineHeight = (int)numericUpDownLineSpacing.Value;
            mbp.Forced = subtitleListView1.Items[_subtitle.GetIndex(p)].Checked;
            mbp.LineJoin = Configuration.Settings.Tools.ExportPenLineJoin;
            var bmp = GenerateImageFromTextWithStyle(mbp);
            if (_exportType == "VOBSUB" || _exportType == "STL" || _exportType == "SPUMUX")
            {
                var nbmp = new NikseBitmap(bmp);
                nbmp.ConverToFourColors(Color.Transparent, _subtitleColor, _borderColor, !checkBoxTransAntiAliase.Checked);
                var temp = nbmp.GetBitmap();
                bmp.Dispose();
                return temp;
            }
            return bmp;
        }
Esempio n. 22
0
 private bool IsMatch()
 {
     NikseBitmap nbmp = new NikseBitmap(pictureBoxCharacter.Image as Bitmap);
     foreach (NOcrPoint op in _nocrChar.LinesForeground)
     {
         foreach (Point point in op.ScaledGetPoints(_nocrChar, nbmp.Width, nbmp.Height))
         {
             if (point.X >= 0 && point.Y >= 0 && point.X < nbmp.Width && point.Y < nbmp.Height)
             {
                 Color c = nbmp.GetPixel(point.X, point.Y);
                 if (c.A > 150 && c.R + c.G + c.B > VobSubOcr.NocrMinColor)
                 {
                 }
                 else
                 {
                     return false;
                 }
             }
         }
     }
     foreach (NOcrPoint op in _nocrChar.LinesBackground)
     {
         foreach (Point point in op.ScaledGetPoints(_nocrChar, nbmp.Width, nbmp.Height))
         {
             if (point.X >= 0 && point.Y >= 0 && point.X < nbmp.Width && point.Y < nbmp.Height)
             {
                 Color c = nbmp.GetPixel(point.X, point.Y);
                 if (c.A > 150 && c.R + c.G + c.B > VobSubOcr.NocrMinColor)
                 {
                     return false;
                 }
             }
         }
     }
     return true;
 }
Esempio n. 23
0
        private void GeneratePreview()
        {
            SetupImageParameters();
            if (subtitleListView1.SelectedItems.Count > 0)
            {
                MakeBitmapParameter mbp;
                var bmp = GenerateImageFromTextWithStyle(_subtitle.Paragraphs[subtitleListView1.SelectedItems[0].Index], out mbp);
                if (checkBoxFullFrameImage.Visible && checkBoxFullFrameImage.Checked)
                {
                    var nbmp = new NikseBitmap(bmp);
                    nbmp.ReplaceTransparentWith(panelFullFrameBackground.BackColor);
                    bmp.Dispose();
                    bmp = nbmp.GetBitmap();
                }
                else
                {
                    groupBoxExportImage.BackColor = DefaultBackColor;
                }
                pictureBox1.Image = bmp;

                int w = groupBoxExportImage.Width - 4;
                pictureBox1.Width = bmp.Width;
                pictureBox1.Height = bmp.Height;
                pictureBox1.Top = groupBoxExportImage.Height - bmp.Height - int.Parse(comboBoxBottomMargin.Text);
                pictureBox1.Left = (w - bmp.Width) / 2;
                var alignment = GetAlignmentFromParagraph(mbp, _format, _subtitle);

                // fix alignment from UI
                if (comboBoxHAlign.Visible && alignment == ContentAlignment.BottomCenter && _format.GetType() != typeof(AdvancedSubStationAlpha) && _format.GetType() != typeof(SubStationAlpha))
                {
                    if (comboBoxHAlign.SelectedIndex == 0)
                    {
                        alignment = ContentAlignment.BottomLeft;
                    }
                    else if (comboBoxHAlign.SelectedIndex == 2)
                    {
                        alignment = ContentAlignment.BottomRight;
                    }
                }

                if (comboBoxHAlign.Visible)
                {
                    if (comboBoxLeftRightMargin.Visible)
                    {
                        if (alignment == ContentAlignment.BottomLeft || alignment == ContentAlignment.MiddleLeft || alignment == ContentAlignment.TopLeft)
                            pictureBox1.Left = int.Parse(comboBoxLeftRightMargin.Text);
                        else if (alignment == ContentAlignment.BottomRight || alignment == ContentAlignment.MiddleRight || alignment == ContentAlignment.TopRight)
                            pictureBox1.Left = w - bmp.Width - int.Parse(comboBoxLeftRightMargin.Text);
                    }

                    if (alignment == ContentAlignment.MiddleLeft || alignment == ContentAlignment.MiddleCenter || alignment == ContentAlignment.MiddleRight)
                        pictureBox1.Top = (groupBoxExportImage.Height - 4 - bmp.Height) / 2;
                    else if (comboBoxBottomMargin.Visible && alignment == ContentAlignment.TopLeft || alignment == ContentAlignment.TopCenter || alignment == ContentAlignment.TopRight)
                        pictureBox1.Top = int.Parse(comboBoxBottomMargin.Text);
                }
                if (bmp.Width > groupBoxExportImage.Width + 20 || bmp.Height > groupBoxExportImage.Height + 20)
                {
                    pictureBox1.Left = 5;
                    pictureBox1.Top = 20;
                    pictureBox1.Width = groupBoxExportImage.Width - 10;
                    pictureBox1.Height = groupBoxExportImage.Height - 30;
                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                }
                else
                {
                    pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
                }
                groupBoxExportImage.Text = string.Format("{0}x{1}", bmp.Width, bmp.Height);
                if (!string.IsNullOrEmpty(mbp.Error))
                {
                    groupBoxExportImage.BackColor = Color.Red;
                    groupBoxExportImage.Text = groupBoxExportImage.Text + " - " + mbp.Error;
                }
                else
                {
                    if (checkBoxFullFrameImage.Visible && checkBoxFullFrameImage.Checked)
                    {
                        groupBoxExportImage.BackColor = panelFullFrameBackground.BackColor;
                    }
                    else
                    {
                        groupBoxExportImage.BackColor = groupBoxImageSettings.BackColor;
                    }
                }
            }
        }
Esempio n. 24
0
        private void listBoxFileNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            labelNOcrCharInfo.Text = string.Empty;
            if (listBoxFileNames.SelectedIndex < 0)
                return;

            _nocrChar = listBoxFileNames.Items[listBoxFileNames.SelectedIndex] as NOcrChar;
            if (_nocrChar == null)
            {
                pictureBoxCharacter.Invalidate();
                groupBoxCurrentCompareImage.Enabled = false;
                listBoxLinesForeground.Items.Clear();
                listBoxlinesBackground.Items.Clear();
            }
            else
            {
                textBoxText.Text = _nocrChar.Text;
                checkBoxItalic.Checked = _nocrChar.Italic;
                pictureBoxCharacter.Invalidate();
                groupBoxCurrentCompareImage.Enabled = true;
                labelNOcrCharInfo.Text = string.Format("Size: {0}x{1}, margin top: {2} ", _nocrChar.Width, _nocrChar.Height, _nocrChar.MarginTop);

                if (pictureBoxCharacter.Image != null)
                {
                    if (IsMatch())
                    {
                        groupBoxCurrentCompareImage.BackColor = Color.LightGreen;
                    }
                    else
                    {
                        groupBoxCurrentCompareImage.BackColor = Control.DefaultBackColor;
                    }
                }
                _drawLineOn = false;
                _history = new List<NOcrChar>();
                _historyIndex = -1;

                if (_bitmap == null)
                {
                    var bitmap = new Bitmap(_nocrChar.Width, _nocrChar.Height);
                    var nbmp = new NikseBitmap(bitmap);
                    nbmp.Fill(Color.White);
                    pictureBoxCharacter.Image = nbmp.GetBitmap();
                    SizePictureBox();
                    ShowOcrPoints();
                    bitmap.Dispose();
                }
            }
        }
Esempio n. 25
0
 private void SaveImage(Bitmap bmp, string fileName, ImageFormat imageFormat)
 {
     if (Equals(imageFormat, ImageFormat.Icon))
     {
         var nikseBitmap = new NikseBitmap(bmp);
         nikseBitmap.SaveAsTarga(fileName);
     }
     else
     {
         bmp.Save(fileName, imageFormat);
     }
 }
Esempio n. 26
0
        public NOcrChar GetMatch(NikseBitmap nbmp)
        {
            const int NocrMinColor = 300;
            const int topMargin = 1;
            double widthPercent = nbmp.Height * 100.0 / nbmp.Width;

            foreach (NOcrChar oc in OcrCharacters)
            {
                if (Math.Abs(widthPercent - oc.WidthPercent) < 20 && Math.Abs(oc.MarginTop - topMargin) < 5)
                { // only very accurate matches

                    bool ok = true;
                    var index = 0;
                    while (index < oc.LinesForeground.Count && ok)
                    {
                        NOcrPoint op = oc.LinesForeground[index];
                        foreach (Point point in op.ScaledGetPoints(oc, nbmp.Width, nbmp.Height))
                        {
                            if (point.X >= 0 && point.Y >= 0 && point.X < nbmp.Width && point.Y < nbmp.Height)
                            {
                                Color c = nbmp.GetPixel(point.X, point.Y);
                                if (c.A > 150 && c.R + c.G + c.B > NocrMinColor)
                                {
                                }
                                else
                                {
                                    Point p = new Point(point.X - 1, point.Y);
                                    if (p.X < 0)
                                        p.X = 1;
                                    c = nbmp.GetPixel(p.X, p.Y);
                                    if (nbmp.Width > 20 && c.A > 150 && c.R + c.G + c.B > NocrMinColor)
                                    {
                                    }
                                    else
                                    {
                                        ok = false;
                                        break;
                                    }
                                }
                            }
                        }
                        index++;
                    }
                    index = 0;
                    while (index < oc.LinesBackground.Count && ok)
                    {
                        NOcrPoint op = oc.LinesBackground[index];
                        foreach (Point point in op.ScaledGetPoints(oc, nbmp.Width, nbmp.Height))
                        {
                            if (point.X >= 0 && point.Y >= 0 && point.X < nbmp.Width && point.Y < nbmp.Height)
                            {
                                Color c = nbmp.GetPixel(point.X, point.Y);
                                if (c.A > 150 && c.R + c.G + c.B > NocrMinColor)
                                {
                                    Point p = new Point(point.X, point.Y);
                                    if (oc.Width > 19 && point.X > 0)
                                        p.X = p.X - 1;
                                    c = nbmp.GetPixel(p.X, p.Y);
                                    if (c.A > 150 && c.R + c.G + c.B > NocrMinColor)
                                    {
                                        ok = false;
                                        break;
                                    }
                                }
                            }
                        }
                        index++;
                    }
                    if (ok)
                        return oc;
                }
            }
            return null;
        }
Esempio n. 27
0
        private static int CalcWidthViaDraw(string text, MakeBitmapParameter parameter)
        {
            //text = HtmlUtil.RemoveHtmlTags(text, true).Trim();
            text = text.Trim();
            var path = new GraphicsPath();
            var sb = new StringBuilder();
            int i = 0;
            bool isItalic = false;
            bool isBold = parameter.SubtitleFontBold;
            const float top = 5f;
            bool newLine = false;
            float left = 1.0f;
            float leftMargin = left;
            int newLinePathPoint = -1;
            Color c = parameter.SubtitleColor;
            var colorStack = new Stack<Color>();
            var lastText = new StringBuilder();
            var sf = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Near };
            var bmp = new Bitmap(parameter.ScreenWidth, 200);
            var g = Graphics.FromImage(bmp);

            g.CompositingQuality = CompositingQuality.HighSpeed;
            g.SmoothingMode = SmoothingMode.HighSpeed;
            g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

            Font font = SetFont(parameter, parameter.SubtitleFontSize);
            while (i < text.Length)
            {
                if (text.Substring(i).StartsWith("<font ", StringComparison.OrdinalIgnoreCase))
                {
                    float addLeft = 0;
                    int oldPathPointIndex = path.PointCount;
                    if (oldPathPointIndex < 0)
                        oldPathPointIndex = 0;

                    if (sb.Length > 0)
                    {
                        lastText.Append(sb);
                        TextDraw.DrawText(font, sf, path, sb, isItalic, parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    if (path.PointCount > 0)
                    {
                        var list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                        for (int k = oldPathPointIndex; k < list.Length; k++)
                        {
                            if (list[k].X > addLeft)
                                addLeft = list[k].X;
                        }
                    }
                    if (path.PointCount == 0)
                        addLeft = left;
                    else if (addLeft < 0.01)
                        addLeft = left + 2;
                    left = addLeft;

                    DrawShadowAndPath(parameter, g, path);
                    var p2 = new SolidBrush(c);
                    g.FillPath(p2, path);
                    p2.Dispose();
                    path.Reset();
                    path = new GraphicsPath();
                    sb = new StringBuilder();

                    int endIndex = text.Substring(i).IndexOf('>');
                    if (endIndex < 0)
                    {
                        i += 9999;
                    }
                    else
                    {
                        string fontContent = text.Substring(i, endIndex);
                        if (fontContent.Contains(" color="))
                        {
                            string[] arr = fontContent.Substring(fontContent.IndexOf(" color=", StringComparison.Ordinal) + 7).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (arr.Length > 0)
                            {
                                string fontColor = arr[0].Trim('\'').Trim('"').Trim('\'');
                                try
                                {
                                    colorStack.Push(c); // save old color
                                    if (fontColor.StartsWith("rgb("))
                                    {
                                        arr = fontColor.Remove(0, 4).TrimEnd(')').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                        c = Color.FromArgb(int.Parse(arr[0]), int.Parse(arr[1]), int.Parse(arr[2]));
                                    }
                                    else
                                    {
                                        c = ColorTranslator.FromHtml(fontColor);
                                    }
                                }
                                catch
                                {
                                    c = parameter.SubtitleColor;
                                }
                            }
                        }
                        i += endIndex;
                    }
                }
                else if (text.Substring(i).StartsWith("</font>", StringComparison.OrdinalIgnoreCase))
                {
                    if (text.Substring(i).ToLower().Replace("</font>", string.Empty).Length > 0)
                    {
                        if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                        {
                            string t = sb.ToString();
                            sb.Clear();
                            sb.Append(' ');
                            sb.Append(t);
                        }

                        float addLeft = 0;
                        int oldPathPointIndex = path.PointCount - 1;
                        if (oldPathPointIndex < 0)
                            oldPathPointIndex = 0;
                        if (sb.Length > 0)
                        {
                            if (lastText.Length > 0 && left > 2)
                                left -= 1.5f;

                            lastText.Append(sb);

                            TextDraw.DrawText(font, sf, path, sb, isItalic, parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                        }
                        if (path.PointCount > 0)
                        {
                            var list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                            for (int k = oldPathPointIndex; k < list.Length; k++)
                            {
                                if (list[k].X > addLeft)
                                    addLeft = list[k].X;
                            }
                        }
                        if (addLeft < 0.01)
                            addLeft = left + 2;
                        left = addLeft;

                        DrawShadowAndPath(parameter, g, path);
                        g.FillPath(new SolidBrush(c), path);
                        path.Reset();
                        sb = new StringBuilder();
                        if (colorStack.Count > 0)
                            c = colorStack.Pop();
                        if (left >= 3)
                            left -= 2.5f;
                    }
                    i += 6;
                }
                else if (text.Substring(i).StartsWith("<i>", StringComparison.OrdinalIgnoreCase))
                {
                    if (sb.Length > 0)
                    {
                        lastText.Append(sb);
                        TextDraw.DrawText(font, sf, path, sb, isItalic, parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    isItalic = true;
                    i += 2;
                }
                else if (text.Substring(i).StartsWith("</i>", StringComparison.OrdinalIgnoreCase) && isItalic)
                {
                    if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                    {
                        string t = sb.ToString();
                        sb.Clear();
                        sb.Append(' ');
                        sb.Append(t);
                    }
                    lastText.Append(sb);
                    TextDraw.DrawText(font, sf, path, sb, isItalic, parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    isItalic = false;
                    i += 3;
                }
                else if (text.Substring(i).StartsWith("<b>", StringComparison.OrdinalIgnoreCase))
                {
                    if (sb.Length > 0)
                    {
                        lastText.Append(sb);
                        TextDraw.DrawText(font, sf, path, sb, isItalic, isBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    isBold = true;
                    i += 2;
                }
                else if (text.Substring(i).StartsWith("</b>", StringComparison.OrdinalIgnoreCase) && isBold)
                {
                    if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                    {
                        string t = sb.ToString();
                        sb.Clear();
                        sb.Append(' ');
                        sb.Append(t);
                    }
                    lastText.Append(sb);
                    TextDraw.DrawText(font, sf, path, sb, isItalic, isBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    isBold = false;
                    i += 3;
                }
                else
                {
                    sb.Append(text[i]);
                }
                i++;
            }
            if (sb.Length > 0)
                TextDraw.DrawText(font, sf, path, sb, isItalic, parameter.SubtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);

            DrawShadowAndPath(parameter, g, path);
            g.FillPath(new SolidBrush(c), path);
            g.Dispose();

            var nbmp = new NikseBitmap(bmp);
            nbmp.CropTransparentSidesAndBottom(0, true);
            bmp.Dispose();
            font.Dispose();
            sf.Dispose();
            return nbmp.Width;
        }
Esempio n. 28
0
 public BinaryOcrBitmap(NikseBitmap nbmp)
 {
     InitializeViaNikseBmp(nbmp);
 }