1. 程式人生 > >C#萬能工具類部分程式碼

C#萬能工具類部分程式碼

							C#萬能工具類
class Utils
{
    //獲取路徑
    public static string GetImagePath()
    {
        string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                     + Path.DirectorySeparatorChar.ToString();
        if (!Directory.Exists(personImgPath))
        {
            Directory.CreateDirectory(personImgPath);
        }
        return personImgPath;
    }

    //字串轉16進位制位元組陣列
    public static byte[] strToToHexByte(string hexString)
    {
        hexString = hexString.Replace(" ", "");
        if ((hexString.Length % 2) != 0)
            hexString += " ";
        byte[] returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return returnBytes;
    }

    // 把位元組型轉換成十六進位制字串 
    public static String byteToChar(uint length, byte[] data)
    {
        StringBuilder stringbuiler = new StringBuilder();
        for (int i = 0; i < length; i++)
        {
            String temp = data[i].ToString("x");
            if (temp.Length == 1)
            {
                stringbuiler.Append("0" + temp);
            }
            else
            {
                stringbuiler.Append(temp);
            }
        }
        return (stringbuiler.ToString());
    }

    //Http
    public static string postdata(string jsonStr, string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.Accept = "application/json";
        request.ContentType = "application/json";
        //如果是get方式就不用一下using內程式碼,將引數在url中傳送
        using (Stream outStream = request.GetRequestStream())
        {
            StreamWriter sw = new StreamWriter(outStream);
            sw.WriteLine(jsonStr);
            sw.Flush();
            sw.Close();
        }
        //獲取伺服器端response的json請求
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (Stream inStream = response.GetResponseStream())
        {
            StreamReader sr = new StreamReader(inStream);
            string resJson = sr.ReadToEnd();
            return resJson;
        }
    }

    /// <summary>
    /// 位元組流轉換成圖片
    /// </summary>
    /// <param name="byt">要轉換的位元組流</param>
    /// <returns>轉換得到的Image物件</returns>
    public static Image BytToImg(byte[] byt)
    {
        MemoryStream ms = new MemoryStream(byt);
        Image img = Image.FromStream(ms);
        return img;
    }

    /// <summary>
    /// 根據圖片路徑返回圖片的位元組流byte[]
    /// </summary>
    /// <param name="imagePath">圖片路徑</param>
    /// <returns>返回的位元組流</returns>
    public static byte[] getImageByte(string imagePath)
    {
        FileStream files = new FileStream(imagePath, FileMode.Open);
        byte[] imgByte = new byte[files.Length];
        files.Read(imgByte, 0, imgByte.Length);
        files.Close();
        return imgByte;
    }

    /// 無失真壓縮圖片    
    /// <param name="sFile">原圖片</param>    
    /// <param name="dFile">壓縮後儲存位置</param>    
    /// <param name="dHeight">高度</param>    
    /// <param name="dWidth"></param>    
    /// <param name="flag">壓縮質量(數字越小壓縮率越高) 1-100</param>    
    /// <returns></returns>    
    public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
    {
        System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
        ImageFormat tFormat = iSource.RawFormat;
        int sW = 0, sH = 0;

        //按比例縮放  
        Size tem_size = new Size(iSource.Width, iSource.Height);

        if (tem_size.Width > dHeight || tem_size.Width > dWidth)
        {
            if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
            {
                sW = dWidth;
                sH = (dWidth * tem_size.Height) / tem_size.Width;
            }
            else
            {
                sH = dHeight;
                sW = (tem_size.Width * dHeight) / tem_size.Height;
            }
        }
        else
        {
            sW = tem_size.Width;
            sH = tem_size.Height;
        }

        Bitmap ob = new Bitmap(dWidth, dHeight);
        Graphics g = Graphics.FromImage(ob);

        g.Clear(Color.WhiteSmoke);
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

        g.Dispose();
        //以下程式碼為儲存圖片時,設定壓縮質量    
        EncoderParameters ep = new EncoderParameters();
        long[] qy = new long[1];
        qy[0] = flag;//設定壓縮的比例1-100    
        EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
        ep.Param[0] = eParam;
        try
        {
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICIinfo = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICIinfo = arrayICI[x];
                    break;
                }
            }
            if (jpegICIinfo != null)
            {
                ob.Save(dFile, jpegICIinfo, ep);//dFile是壓縮後的新路徑    
            }
            else
            {
                ob.Save(dFile, tFormat);
            }
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            iSource.Dispose();
            ob.Dispose();
        }
    }

    /// <summary>
    /// 變成黑白圖
    /// </summary>
    /// <param name="bmp">原始圖</param>
    /// <param name="mode">模式。0:加權平均  1:算數平均</param>
    /// <returns></returns>
    public static Bitmap ToGray(Bitmap bmp, int mode)
    {
        if (bmp == null)
        {
            return null;
        }
        int w = bmp.Width;
        int h = bmp.Height;
        try
        {
            byte newColor = 0;
            BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            unsafe
            {
                byte* p = (byte*)srcData.Scan0.ToPointer();
                for (int y = 0; y < h; y++)
                {
                    for (int x = 0; x < w; x++)
                    {

                        if (mode == 0) // 加權平均
                        {
                            newColor = (byte)((float)p[0] * 0.114f + (float)p[1] * 0.587f + (float)p[2] * 0.299f);
                        }
                        else    // 算數平均
                        {
                            newColor = (byte)((float)(p[0] + p[1] + p[2]) / 3.0f);
                        }
                        p[0] = newColor;
                        p[1] = newColor;
                        p[2] = newColor;

                        p += 3;
                    }
                    p += srcData.Stride - w * 3;
                }
                bmp.UnlockBits(srcData);
                return bmp;
            }
        }
        catch
        {
            return null;
        }

    }

    /// <summary>
    /// 圖片 轉為base64編碼的文字
    /// </summary>
    /// <param name="bmp">待轉的Bitmap</param>
    /// <returns>轉換後的base64字串</returns>
    //public  String ImgToBase64String(Image bmp)
    //{
    //  String strbaser64 = String.Empty;
    //var btarr = convertByte(bmp);
    //strbaser64 = Convert.ToBase64String(btarr);
    //            return strbaser64;
    //      }
}