GetFileSize() public static method

返回文件大小
public static GetFileSize ( string path, string fileName ) : int
path string
fileName string
return int
Example #1
0
        async Task DeployToTargetAsync(DataRecorder record, ICancelable task, SshTarget target,
                                       string localPath, string remotePath, bool force = false)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();

            try
            {
                BinarySignatureCheck.Types.Result signatureCheck = force
                    ? BinarySignatureCheck.Types.Result.AlwaysCopy
                    : BinarySignatureCheck.Types.Result.YesCopy;

                record.SetCopyAttempted(true);
                record.BinarySize(FileUtil.GetFileSize(localPath, _fileSystem));
                record.SignatureCheckResult(signatureCheck);
                record.DeploymentMode();

                await _remoteFile.SyncAsync(target, localPath, remotePath, task, force);

                record.CopyBinary(stopwatch.ElapsedMilliseconds, DataRecorder.NoError);
            }
            catch (ProcessException exception)
            {
                record.CopyBinary(stopwatch.ElapsedMilliseconds, exception);
                throw new DeployException(
                          ErrorStrings.FailedToDeployExecutable(exception.Message),
                          exception);
            }
        }
Example #2
0
        /// <summary>
        ///     递归获取文件信息并返回树型结构
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="tree">树集合</param>
        private void GetFiles(string path,
                              ref List <TreeEntity> tree)
        {
            var strFileNames   = Directory.GetFiles(path);
            var strDirectories = Directory.GetDirectories(path);

            foreach (var filename in strFileNames)
            {
                _treeEntity = new TreeEntity
                {
                    icon = "blue-document-text",
                    id   = filename,
                    pId  = path,
                    name = Path.GetFileName(filename) + "(" + FileUtil.GetFileSize(filename) + ")",
                    url  = filename
                };
                tree.Add(_treeEntity);
            }
            foreach (var dir in strDirectories)
            {
                var directoryName = dir.Substring(dir.LastIndexOf(@"\", StringComparison.Ordinal) + 1);
                _treeEntity = new TreeEntity
                {
                    isParent = true,
                    id       = dir,
                    pId      = path,
                    name     = directoryName
                };
                tree.Add(_treeEntity);
                GetFiles(dir, ref tree);
            }
        }
Example #3
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            long?  fileSize   = value as long?;
            string sizeString = FileUtil.GetFileSize(fileSize);

            return(sizeString);
        }
Example #4
0
 static public int GetFileSize_s(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         System.String a1;
         checkType(l, 1, out a1);
         var ret = FileUtil.GetFileSize(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
Example #5
0
        public CustomFileInfo UpLoadFileInfo(CustomFileInfo fileInfo)
        {
            log.Info("上传文件开始:" + DateTime.Now);
            byte[] bytes = Convert.FromBase64String(fileInfo.SendByteStr);

            string fileName = CommonUtil.GUID() + fileInfo.Extension;

            //log.Info("newbytes:" + newbytes);
            log.Info("图片名字:" + fileName);

            string fullpath = HttpContext.Current.Server.MapPath("~/Upload/") + fileName;

            using (FileStream fileStream = new FileStream(fullpath, FileMode.Create))
            {
                fileStream.Write(bytes, 0, bytes.Length);
            }

            fileInfo.OldName   = fileInfo.OldName;
            fileInfo.NewName   = fileName;
            fileInfo.Extension = fileInfo.Extension;
            fileInfo.Path      = "/Upload/" + fileName;
            fileInfo.FileSize  = FileUtil.GetFileSize(fullpath).ToString();
            fileInfo.SendByte  = null;

            log.Info("上传文件结束:" + DateTime.Now);

            return(fileInfo);
        }
        private long GetCurrentCacheSize()
        {
            List <string> toCleaningFiles = new List <string>();
            long          totalSize       = 0;

            foreach (var keyValuePair in GetCacheFiles())
            {
                toCleaningFiles.AddRange(keyValuePair.Value);
            }

            foreach (var cleaningFile in toCleaningFiles)
            {
                var length = FileUtil.GetFileSize(cleaningFile);
                totalSize += length;
            }

            return(totalSize);
        }
        /// <summary>
        /// 数据库备份
        /// </summary>
        /// <param name="doubleWay"></param>
        /// <returns></returns>
        public async Task <OperateStatus> SystemDataBaseBackUp(SystemDataBaseBackUpDoubleWay doubleWay)
        {
            OperateStatus  operateStatus  = new OperateStatus();
            SystemDataBase systemDataBase = await _systemDataBaseRepository.GetByIdAsync(doubleWay.DataBaseId);

            string bakPath = "\\DataUsers\\DataBaseBackUps\\" + systemDataBase.CatalogName + DateTime.Now.ToString("yyyyMMddhhssmm") + ".bak";

            //开始进行数据库备份操作
            DbBackUpAndRestore.Uid                 = systemDataBase.UserId;
            DbBackUpAndRestore.Database            = systemDataBase.CatalogName;
            DbBackUpAndRestore.Pwd                 = systemDataBase.Password;
            DbBackUpAndRestore.Server              = systemDataBase.DataSource;
            DbBackUpAndRestore.BackUpOrRestorePath = doubleWay.BackUpOrRestorePath + bakPath; //程序根目录地址
            try
            {
                if (DbBackUpAndRestore.Operate())
                {
                    //添加备份记录
                    SystemDataBaseBackUp backUp = new SystemDataBaseBackUp()
                    {
                        BackUpId   = CombUtil.NewComb(),
                        BackUpTime = DateTime.Now,
                        DataBaseId = doubleWay.DataBaseId,
                        From       = (byte)EnumFrom.手动,
                        Name       = systemDataBase.CatalogName + DateTime.Now.ToString("yyyyMMddhhssmm") + ".bak",
                        Path       = DbBackUpAndRestore.BackUpOrRestorePath,
                        Size       = FileUtil.GetFileSize(DbBackUpAndRestore.BackUpOrRestorePath)
                    };
                    operateStatus = await InsertAsync(backUp);
                }
                else
                {
                    operateStatus.Message = Chs.Error;
                }
            }
            catch (Exception ex)
            {
                operateStatus.Message = ex.Message;
            }
            return(operateStatus);
        }
Example #8
0
        /// <summary>
        /// 根据文件名获取单一的文件数据(包含文件字节数据),如果指定了图片的高度,宽度,那么下载缩略图
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public FileUploadInfo DownloadByPath(string filePath, int?width = null, int?height = null)
        {
            FileUploadInfo info = null;

            if (File.Exists(filePath))
            {
                try
                {
                    info            = new FileUploadInfo();
                    info.FileExtend = FileUtil.GetExtension(filePath);
                    info.FileName   = FileUtil.GetFileName(filePath);
                    info.FileSize   = FileUtil.GetFileSize(filePath);
                    info.AddTime    = FileUtil.GetFileCreateTime(filePath);

                    byte[] bytes = FileUtil.FileToBytes(filePath);
                    if (width.HasValue && height.HasValue)
                    {
                        //控制图片的最大尺寸
                        int newwidth  = width.Value > 1024 ? 1024 : width.Value;
                        int newheight = height.Value > 768 ? 768 : height.Value;

                        Image image      = ImageHelper.BitmapFromBytes(bytes);
                        Image smallImage = ImageHelper.ChangeImageSize(image, newwidth, newheight);
                        info.FileData = ImageHelper.ImageToBytes(smallImage);
                    }
                    else
                    {
                        info.FileData = bytes;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
            }
            return(info);
        }
Example #9
0
        /// <summary>
        /// 文件切割
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="outPutPath">输出文件路径</param>
        /// <param name="kbLength">单个子文件最大长度。单位:KB</param>
        /// <param name="delete">标识文件分割完成后是否删除原文件</param>
        /// <param name="change">加密密钥</param>
        private void FileSplit(string filePath, string outPutPath, int kbLength, bool delete, int change)
        {
            if (filePath == null || !File.Exists(filePath))
            {
                return;
            }

            //// 加密初始化
            //short sign = 1;
            //int num = 0, tmp;
            //if (change < 0)
            //{
            //    sign = -1;
            //    change = -change;
            //}

            var fileName = Path.GetFileNameWithoutExtension(filePath);
            var fileSize = FileUtil.GetFileSize(filePath);
            var total    = Conv.ToInt(fileSize.GetSizeByK() / kbLength);

            using (FileStream readStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                byte[]     data = new byte[1024]; // 流读取,缓存空间
                int        len = 0, i = 1;        // 记录子文件累积读取的KB大小,分割的子文件序号
                int        readLen     = 0;       // 每次实际读取的字节大小
                FileStream writeStream = null;
                // 读取数据
                while (readLen > 0 || (readLen = readStream.Read(data, 0, data.Length)) > 0)
                {
                    // 创建分割后的子文件,已有则覆盖
                    if (len == 0 || writeStream == null)
                    {
                        writeStream = new FileStream($"{outPutPath}\\{fileName}.{i++}.{total}.bin", FileMode.Create);
                    }

                    //// 加密逻辑,对data的首字节进行逻辑偏移加密
                    //if (num == 0)
                    //{
                    //    num = change;
                    //}

                    //tmp = data[0] + sign * (num % 3 + 3);
                    //if (tmp > 255)
                    //{
                    //    tmp -= 255;
                    //}
                    //else if(tmp<0)
                    //{
                    //    tmp += 255;
                    //}

                    //data[0] = (byte) tmp;
                    //num /= 3;

                    // 输出,缓存数据写入子文件
                    writeStream.Write(data, 0, readLen);
                    writeStream.Flush();
                    // 预读下一轮缓存数据
                    readLen = readStream.Read(data, 0, data.Length);
                    if (++len >= kbLength || readLen == 0) //子文件达到指定大小,或文件已读完
                    {
                        writeStream.Close();               // 关闭当前输出流
                        len = 0;
                    }
                }
            }

            if (delete)
            {
                FileUtil.Delete(filePath);
            }
        }
Example #10
0
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                //对Winform本地程序来说,有时候文件已经是存在的,且路径已经设置好,
                //因此设置notCopyFile = true, 不需要复制文件从而导致文件路径变动
                bool notCopyFile = Convert.ToBoolean(e.Argument);

                int    step  = 0;
                int    i     = 0;
                string state = "";
                if (fileList.Count > 0)
                {
                    bool   sucess    = true;
                    string lastError = "";
                    foreach (string file in fileList)
                    {
                        FileUploadInfo info = new FileUploadInfo();
                        if (notCopyFile)
                        {
                            //如果不需要复制文件,那么记录文件的相对路径
                            info.BasePath = Path.GetDirectoryName(file);
                        }
                        else
                        {
                            //常规复制文件,需要记录文件的字节
                            info.FileData = FileUtil.FileToBytes(file);
                        }

                        info.FileName       = FileUtil.GetFileName(file);
                        info.Category       = this.AttachmentDirectory;
                        info.FileExtend     = FileUtil.GetExtension(file);
                        info.FileSize       = FileUtil.GetFileSize(file);
                        info.Editor         = UserId; //登录人
                        info.Owner_ID       = OwerId; //所属主表记录ID
                        info.AttachmentGUID = AttachmentGUID;

                        CommonResult result = BLLFactory <FileUpload> .Instance.Upload(info);

                        if (!result.Success)
                        {
                            sucess           = false;
                            lastError        = result.ErrorMessage;
                            fileStatus[file] = result.ErrorMessage;
                            state            = string.Format("{0}|{1}", file, result.ErrorMessage);
                        }
                        else
                        {
                            fileStatus[file] = "成功";
                            state            = string.Format("{0}|成功", file);
                        }

                        i++;
                        step = Convert.ToInt32((100.0 / (fileList.Count * 1.0)) * i);
                        worker.ReportProgress(step, state);
                    }
                    e.Result = sucess ? "Success" : "Failed:" + lastError;
                }
            }
            catch (Exception ex)
            {
                e.Result = ex.Message;
            }
        }
Example #11
0
        protected void RenderMemoryGrid()
        {
            long?driverFileSize;
            long?seqFileSize;
            long?dspFileSize;
            uint?dspRamNeeded;
            long?tonFileSize;

            long  currentOffset = DATA_START_OFFSET;
            float currentHeight = DATA_START_HEIGHT;

            float seqHeight;
            float dspHeight;
            float dspRamHeight;
            float tonHeight;

            Brush rectangleColor;

            // draw white background
            this.graphicsRenderer.FillRectangle(Brushes.White, 0, 0, RECT_WIDTH, RECT_HEIGHT);

            #region Render Driver
            if (!String.IsNullOrEmpty(this.tbDriverFile.Text))
            {
                driverFileSize = FileUtil.GetFileSize(this.tbDriverFile.Text);

                if (driverFileSize != null)
                {
                    if (driverFileSize > TOTAL_68000_MEMORY)
                    {
                        rectangleColor = Brushes.Red;
                    }
                    else
                    {
                        rectangleColor = Brushes.Aqua;
                    }

                    this.graphicsRenderer.FillRectangle(rectangleColor, 0, 0, RECT_WIDTH, this.GetRectangleHeight((float)driverFileSize));
                }
            }
            #endregion

            #region Render SEQ
            if (!String.IsNullOrEmpty(this.tbSequenceFile.Text))
            {
                seqFileSize = FileUtil.GetFileSize(this.tbSequenceFile.Text);

                if (seqFileSize != null)
                {
                    if ((currentOffset + seqFileSize) > TOTAL_68000_MEMORY)
                    {
                        rectangleColor = Brushes.Red;
                    }
                    else
                    {
                        rectangleColor = Brushes.BlueViolet;
                    }

                    seqHeight = this.GetRectangleHeight((float)seqFileSize);
                    this.graphicsRenderer.FillRectangle(rectangleColor, 0, currentHeight, RECT_WIDTH, seqHeight);

                    // update current offset/hieght
                    currentOffset += (long)seqFileSize;
                    currentHeight += seqHeight;
                }
            }
            #endregion

            #region Render DSP
            if (!String.IsNullOrEmpty(this.tbDspProgram.Text))
            {
                dspFileSize = FileUtil.GetFileSize(this.tbDspProgram.Text);

                // shoudl do some error handling around this
                dspRamNeeded = SegaSaturnSequence.GetDspRamNeeded(this.tbDspProgram.Text);

                if (dspFileSize != null)
                {
                    currentOffset = MathUtil.RoundUpToByteAlignment((long)currentOffset, 0x2000);
                    currentHeight = GetRectangleHeight(currentOffset);

                    if ((currentOffset + dspFileSize) > TOTAL_68000_MEMORY)
                    {
                        rectangleColor = Brushes.Red;
                    }
                    else
                    {
                        rectangleColor = Brushes.DarkKhaki;
                    }

                    dspHeight = this.GetRectangleHeight((float)dspFileSize);
                    this.graphicsRenderer.FillRectangle(rectangleColor, 0, currentHeight, RECT_WIDTH, dspHeight);

                    // update current offset/height
                    currentOffset += (long)dspFileSize;
                    currentHeight += dspHeight;

                    // handle DSP RAM
                    dspRamHeight = this.GetRectangleHeight((float)dspRamNeeded);

                    if ((currentOffset + dspRamHeight) > TOTAL_68000_MEMORY)
                    {
                        rectangleColor = Brushes.Red;
                    }
                    else
                    {
                        rectangleColor = Brushes.Lime;
                    }

                    this.graphicsRenderer.FillRectangle(rectangleColor, 0, currentHeight, RECT_WIDTH, dspRamHeight);
                    this.graphicsRenderer.DrawString("DSP RAM", new Font(FontFamily.GenericSansSerif, 7), Brushes.Black, 5, currentHeight + 1);

                    currentOffset += (long)dspRamNeeded;
                    currentHeight += dspRamHeight;
                }
            }
            #endregion

            #region Render TON

            if (this.lbToneData.Items.Count > 0)
            {
                foreach (ListBoxFileInfoObject listFileObject in this.lbToneData.Items)
                {
                    tonFileSize = FileUtil.GetFileSize(listFileObject.FilePath);

                    if (tonFileSize != null)
                    {
                        if ((currentOffset + tonFileSize) > TOTAL_68000_MEMORY)
                        {
                            rectangleColor = Brushes.Red;
                        }
                        else
                        {
                            rectangleColor = Brushes.Plum;
                        }

                        tonHeight = this.GetRectangleHeight((float)tonFileSize);
                        this.graphicsRenderer.FillRectangle(rectangleColor, 0, currentHeight, RECT_WIDTH, tonHeight);

                        // update current offset/hieght
                        currentOffset += (long)tonFileSize;
                        currentHeight += tonHeight;
                    }
                }
            }

            #endregion

            //render outline
            this.graphicsRenderer.DrawRectangle(this.blackPen, 0, 0, RECT_WIDTH - this.blackPen.Width, RECT_HEIGHT - this.blackPen.Width);

            // repaint
            this.pb68000Memory.Refresh();
        }
Example #12
0
        /// <summary>
        /// Upload/download blob files
        /// <param name="initSize"></param>
        /// <param name="endSize"></param>
        /// <param name="unit">"K", "M", "G", "G_BLOCK", "G_PAGE"</param>
        /// </summary>
        public void TransferTestFiles(int initSize, int endSize, string unit, Dictionary <long, double> fileSizeTime,
                                      Dictionary <long, double> fileSizeTimeSD, ICLIOperation operation, ICLIOperation reverseOperation = null, int?iteration = null)
        {
            var containerName = DownloadContainerPrefix;

            if (operation.IsUploadTest)
            {
                containerName = UploadContainerPrefix;
            }

            for (int i = initSize; i <= endSize; i *= 4)
            {
                string fileName = "testfile_" + i + unit;

                long fileSize = 0L;
                if (operation.IsUploadTest)
                {
                    if (!FileUtil.FileExists(fileName))
                    {
                        throw new Exception("file not found, path: " + fileName);
                    }
                    else
                    {
                        fileSize = FileUtil.GetFileSize(fileName);
                    }
                }
                else if (this.GenerateDataBeforeDownload && reverseOperation != null)
                {
                    reverseOperation.Before(containerName, fileName);
                    reverseOperation.Go(containerName, fileName);
                }

                List <long> fileTimeList = new List <long>();

                Stopwatch sw = new Stopwatch();

                var iterations = iteration.HasValue ? iteration.Value : Constants.Iterations;
                for (int j = 0; j < iterations; j++)
                {
                    operation.Before(containerName, fileName);

                    sw.Reset(); sw.Start();
                    var bSuccess = operation.Go(
                        containerName: containerName,
                        fileName: fileName);

                    Test.Assert(bSuccess, operation.Name + " should succeed");


                    sw.Stop();
                    fileTimeList.Add(sw.ElapsedMilliseconds);

                    var error = string.Empty;
                    Test.Assert(operation.Validate(containerName, fileName, out error), error);

                    Test.Info("file name : {0} round : {1} time(ms) : {2}", fileName, j + 1, sw.ElapsedMilliseconds);
                }
                double average = fileTimeList.Average();

                if (!operation.IsUploadTest)
                {
                    fileSize = FileUtil.GetFileSize(fileName);
                }

                fileSizeTime.Add(fileSize, average);
                var    deviation = fileTimeList.Select(num => Math.Pow(num - average, 2));
                double sd        = Math.Sqrt(deviation.Average());
                fileSizeTimeSD.Add(fileSize, sd);
                Test.Info("file name : {0} average time : {1}", fileName, average);
                Test.Info("file name : {0} standard dev : {1}", fileName, sd);
            }
        }
Example #13
0
 public void WhenFileIsProvidedGetFileSizeShouldReturnFileSize()
 {
     Assert.AreEqual(97.66M, Math.Round(FileUtil.GetFileSize("Dummy\\UTF32.txt", Magnitude.KB), 2));
 }
Example #14
0
 public void WhenNullPathIsProvidedGetFileSizeShouldThrowException()
 {
     Assert.ThrowsException <ArgumentNullException>(() => FileUtil.GetFileSize(null));
 }
Example #15
0
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                //对Winform本地程序来说,有时候文件已经是存在的,且路径已经设置好,
                //因此设置notCopyFile = true, 不需要复制文件从而导致文件路径变动
                bool notCopyFile = Convert.ToBoolean(e.Argument);

                int    step  = 0;
                int    i     = 0;
                string state = "";
                if (fileList.Count > 0)
                {
                    bool   sucess    = true;
                    string lastError = "";
                    foreach (string file in fileList)
                    {
                        FileUploadInfo info = new FileUploadInfo();
                        if (notCopyFile)
                        {
                            //如果不需要复制文件,那么记录文件的相对路径
                            info.BasePath = Path.GetDirectoryName(file);
                        }
                        else
                        {
                            // 常规复制文件,需要记录文件的字节
                            info.FileData = FileUtil.FileToBytes(file);
                        }

                        info.Name           = FileUtil.GetFileName(file);
                        info.FileUploadType = (short)AttachmentDirectory;
                        info.FileExtend     = FileUtil.GetExtension(file);
                        info.FileSize       = FileUtil.GetFileSize(file);
                        info.EditorId       = UserId;    //登录人
                        info.CreatorId      = CreatorId; //所属主表记录ID
                        info.AttachmentGid  = AttachmentGid;

                        /*ReturnResult result = BLLFactory<FileUpload>.Instance.Upload(info);
                         * if (result.ErrorCode != 0)
                         * {
                         *  sucess = false;
                         *  lastError = result.ErrorMessage;
                         *  fileStatus[file] = result.ErrorMessage;
                         *  state = string.Format("{0}|{1}", file, result.ErrorMessage);
                         * }
                         * else
                         * {
                         *  fileStatus[file] = "成功";
                         *  state = string.Format("{0}|成功", file);
                         * }*/

                        i++;
                        step = Convert.ToInt32((100.0 / (fileList.Count * 1.0)) * i);
                        worker.ReportProgress(step, state);
                    }
                    e.Result = sucess ? "上传成功" : "操作失败:" + lastError;
                }
            }
            catch (Exception ex)
            {
                e.Result = ex.Message;
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmUploadFile));
                MessageDxUtil.ShowError(ex.Message);
            }
        }
Example #16
0
        private void SetFlagsFromFileName(string inpFileName)
        {
            if (FileUtil.GetFileSize(inpFileName) > 2058)
            {
                return; // 24*20*4(ARGB)=1920
            }
            Bitmap bmp; try { bmp = (Bitmap)Image.FromFile(inpFileName); }

#pragma warning disable CA1031 // Do not catch general exception types
            catch { return; }
#pragma warning restore CA1031 // Do not catch general exception types

            if (bmp.Width != 24 || bmp.Height != 20)
            {
                return;
            }

            byte[] BrightMap    = new byte[480];
            byte[] BrightCount  = new byte[0x100];
            byte[] iBrightCount = new byte[0x100];
            for (int iy = 0; iy < 20; iy++)
            {
                for (int ix = 0; ix < 24; ix++)
                {
                    var ig = (byte)(0xFF * bmp.GetPixel(ix, iy).GetBrightness());
                    BrightMap[ix + (24 * iy)] = ig;
                    BrightCount[ig]++;
                }
            }

            int ColorCount = BrightCount.Count(v => v > 0);
            if (ColorCount is 0 or > 4)
            {
                return;
            }
            int    errmin = int.MaxValue;
            byte[] LCT    = new byte[4];
            byte[] mLCT   = new byte[4];
            for (int i = 0; i < 4; i++)
            {
                LCT[i] = (byte)(ColorCount < i + 1 ? 4 : ColorCount - i - 1);
            }
            int ee = 0;
            while (++ee < 1000)
            {
                BrightCount.CopyTo(iBrightCount, 0);
                for (int i = 0, j = 0; i < 0x100; i++)
                {
                    if (iBrightCount[i] > 0)
                    {
                        iBrightCount[i] = LCT[j++];
                    }
                }

                var errtot = 0;
                for (int i = 0; i < 480; i++)
                {
                    errtot += Math.Abs(BrightMap[i] - ColorTable[iBrightCount[BrightMap[i]]]);
                }
                if (errmin > errtot)
                {
                    errmin = errtot;
                    LCT.CopyTo(mLCT, 0);
                }
                LCT = GetNextLCT(LCT);
                if (LCT[0] >= 4)
                {
                    break;
                }
            }
            for (int i = 0, j = 0; i < 0x100; i++)
            {
                if (BrightCount[i] > 0)
                {
                    BrightCount[i] = mLCT[j++];
                }
            }

            for (int i = 0; i < 480; i++)
            {
                BrightMap[i] = BrightCount[BrightMap[i]];
            }

            byte[] ndab = new byte[120];
            for (int i = 0; i < 480; i++)
            {
                ndab[i >> 2] |= (byte)((BrightMap[i] & 3) << (i % 4 << 1));
            }

            ndab.CopyTo(DotArtistByte, 0);
        }
Example #17
0
        private void SetFlagsFromFileName(string inpFileName)
        {
            if (FileUtil.GetFileSize(inpFileName) > 2058)
            {
                return; // 24*20*4(ARGB)=1920
            }
            Bitmap bmp; try { bmp = (Bitmap)Image.FromFile(inpFileName); }

            catch { return; }

            if (bmp.Width != 24 || bmp.Height != 20)
            {
                return;
            }

            Span <byte> BrightMap    = stackalloc byte[480];
            Span <byte> BrightCount  = stackalloc byte[0x100];
            Span <byte> iBrightCount = stackalloc byte[0x100];

            for (int iy = 0; iy < 20; iy++)
            {
                for (int ix = 0; ix < 24; ix++)
                {
                    var ig = (byte)(0xFF * bmp.GetPixel(ix, iy).GetBrightness());
                    BrightMap[ix + (24 * iy)] = ig;
                    BrightCount[ig]++;
                }
            }

            int ColorCount = 0;

            foreach (var value in BrightCount)
            {
                if (value > 0)
                {
                    ++ColorCount;
                }
            }

            if (ColorCount is 0 or > 4)
            {
                return;
            }
            int         errmin = int.MaxValue;
            Span <byte> LCT    = stackalloc byte[4];
            Span <byte> mLCT   = stackalloc byte[4];

            for (int i = 0; i < 4; i++)
            {
                LCT[i] = (byte)(ColorCount < i + 1 ? 4 : ColorCount - i - 1);
            }
            int ee = 0;

            while (++ee < 1000)
            {
                BrightCount.CopyTo(iBrightCount);
                for (int i = 0, j = 0; i < 0x100; i++)
                {
                    if (iBrightCount[i] > 0)
                    {
                        iBrightCount[i] = LCT[j++];
                    }
                }

                var errtot = 0;
                for (int i = 0; i < 480; i++)
                {
                    errtot += Math.Abs(BrightMap[i] - ColorTable[iBrightCount[BrightMap[i]]]);
                }
                if (errmin > errtot)
                {
                    errmin = errtot;
                    LCT.CopyTo(mLCT);
                }
                GetNextLCT(LCT);
                if (LCT[0] >= 4)
                {
                    break;
                }
            }
            for (int i = 0, j = 0; i < 0x100; i++)
            {
                if (BrightCount[i] > 0)
                {
                    BrightCount[i] = mLCT[j++];
                }
            }

            for (int i = 0; i < 480; i++)
            {
                BrightMap[i] = BrightCount[BrightMap[i]];
            }

            Span <byte> ndab = stackalloc byte[120];

            for (int i = 0; i < 480; i++)
            {
                ndab[i >> 2] |= (byte)((BrightMap[i] & 3) << (i % 4 << 1));
            }

            ndab.CopyTo(DotArtistByte.AsSpan(0));
        }