问题描述
解决方案
解决方案二:
publicstaticBitmapMonochromeLockBits(Bitmappimage){Bitmapsource=null;//Iforiginalbitmapisnotalreadyin32BPP,ARGBformat,thenconvertif(pimage.PixelFormat!=PixelFormat.Format32bppArgb){source=newBitmap(pimage.Width,pimage.Height,PixelFormat.Format32bppArgb);source.SetResolution(pimage.HorizontalResolution,pimage.VerticalResolution);using(Graphicsg=Graphics.FromImage(source)){g.DrawImageUnscaled(pimage,0,0);}}else{source=pimage;}//LocksourcebitmapinmemoryBitmapDatasourceData=source.LockBits(newRectangle(0,0,source.Width,source.Height),ImageLockMode.ReadOnly,PixelFormat.Format32bppArgb);//CopyimagedatatobinaryarrayintimageSize=sourceData.Stride*sourceData.Height;byte[]sourceBuffer=newbyte[imageSize];Marshal.Copy(sourceData.Scan0,sourceBuffer,0,imageSize);//Unlocksourcebitmapsource.UnlockBits(sourceData);//CreatedestinationbitmapBitmapdestination=newBitmap(source.Width,source.Height,PixelFormat.Format1bppIndexed);//LockdestinationbitmapinmemoryBitmapDatadestinationData=destination.LockBits(newRectangle(0,0,destination.Width,destination.Height),ImageLockMode.WriteOnly,PixelFormat.Format1bppIndexed);//CreatedestinationbufferimageSize=destinationData.Stride*destinationData.Height;byte[]destinationBuffer=newbyte[imageSize];intsourceIndex=0;intdestinationIndex=0;intpixelTotal=0;bytedestinationValue=0;intpixelValue=128;intheight=source.Height;intwidth=source.Width;intthreshold=500;//Iteratelinesfor(inty=0;y<height;y++){sourceIndex=y*sourceData.Stride;destinationIndex=y*destinationData.Stride;destinationValue=0;pixelValue=128;//Iteratepixelsfor(intx=0;x<width;x++){//Computepixelbrightness(i.e.totalofRed,Green,andBluevalues)pixelTotal=sourceBuffer[sourceIndex+1]+sourceBuffer[sourceIndex+2]+sourceBuffer[sourceIndex+3];if(pixelTotal>threshold){destinationValue+=(byte)pixelValue;}if(pixelValue==1){destinationBuffer[destinationIndex]=destinationValue;destinationIndex++;destinationValue=0;pixelValue=128;}else{pixelValue>>=1;}sourceIndex+=4;}if(pixelValue!=128){destinationBuffer[destinationIndex]=destinationValue;}}//CopybinaryimagedatatodestinationbitmapMarshal.Copy(destinationBuffer,0,destinationData.Scan0,imageSize);//Unlockdestinationbitmapdestination.UnlockBits(destinationData);//Disposeofsourceifnotoriginallysuppliedbitmapif(source!=pimage){source.Dispose();}//Returnreturndestination;}
复制别人的