libtiff 生成48位色tif图片

BOOL CTifImage_48Bits::BitmapConvertTo48BitsTif(CString strImagePath, int nWidth, int nHeight, int nBpp, BYTE* pData)
{
  if (nBpp != 24)
  {
    AfxMessageBox(L"只支持24位真彩图!");
    return FALSE;
  }
 
  if (pData == NULL)
  {
    AfxMessageBox(L"内存段为空!");
    return FALSE;
  }
 
// 调整文件路径名称
  int nFind = strImagePath.ReverseFind('.');
  if (nFind == -1)
  {
    return FALSE;  
  }
 
  CString strExt = strImagePath.Mid(nFind + 1);
  strExt.MakeLower();
  if (strExt != L"tif" && strExt != L"tiff")
  {
    strImagePath = strImagePath.Left(nFind + 1);
    strImagePath += L"tiff";
  }
 
// 转换图像文件路径格式
  LPSTR ppszA = '\0';
  UnicodeToAnsi(strImagePath.GetBuffer(0),&ppszA);
 
  TIFF *image;
 
// 打开一个tif文件
  if((image = TIFFOpen(ppszA, "w")) == NULL)
  { 
    AfxMessageBox(L"不能创建TIF文件!"); 
    return FALSE;
  } 
 
  const int nTifBit = 6;
 
// 分配内存
  DWORD dwImgSize = nWidth * nHeight * nTifBit;
  BYTE* pTifBuf = new BYTE[dwImgSize];
  if (pTifBuf == NULL)
  {
    AfxMessageBox(L"内存分配不足!");
    return FALSE;
  }
 
  memset(pTifBuf, 0, dwImgSize);
 
  int nWidthBytes24 = (( nWidth * nBpp + 31) / 32) * 4;
  int nWidthBytes48 = nWidth * nTifBit;
 
// 复制图像数据
  BYTE* pSrc = (pData);
  BYTE* pDst = (pTifBuf);
 
  int tmpSrc = 0;
  int tmpDst = 0;
 
  for (int j = 0; j < nHeight; j++)
  {
    tmpSrc = 0;
    tmpDst = 0;
 
    for (int i = 0; i < nWidth; i++)
    {
//  // RGBRGB,PhotoShop支持,但是未能实现
//  pDst[tmpDst + 2] = pDst[tmpDst + 5] = pSrc[tmpSrc];
//  pDst[tmpDst + 1] = pDst[tmpDst + 4] = pSrc[tmpSrc + 1];
//  pDst[tmpDst + 0] = pDst[tmpDst + 3] = pSrc[tmpSrc + 2];
 
// RRGGBB
      pDst[tmpDst + 4] = pDst[tmpDst + 5] = pSrc[tmpSrc];
      pDst[tmpDst + 2] = pDst[tmpDst + 3] = pSrc[tmpSrc + 1];
      pDst[tmpDst + 0] = pDst[tmpDst + 1] = pSrc[tmpSrc + 2];
 
      tmpSrc += 3;
      tmpDst += 6;
    }
 
    pSrc -= nWidthBytes24;
    pDst += nWidthBytes48;
  }
// 设置图像宽度.
  TIFFSetField(image, TIFFTAG_IMAGEWIDTH, nWidth); 
 
// 设置图像高度.
  TIFFSetField(image, TIFFTAG_IMAGELENGTH, nHeight); 
 
// 设置一个样本所占内存的大小.
  TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, 16); 
 
// 设置一个像素点的样本数.
  TIFFSetField(image, TIFFTAG_SAMPLESPERPIXEL, nTifBit / 2); 
 
// 设置图像的压缩方式.
  TIFFSetField(image, TIFFTAG_COMPRESSION, COMPRESSION_NONE); 
 
// 设置色彩模式.
  TIFFSetField(image, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); 
 
// 设置配置
  TIFFSetField(image, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
 
// 设置Planar配置.
  TIFFSetField(image, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); 
 
  int32 iTiffCount = TIFFWriteEncodedStrip(image, 0, pTifBuf, nWidth * nHeight * nTifBit); 
 
  TIFFClose(image); 
 
  delete pTifBuf;
  pTifBuf = NULL;
 
// 如果返回值大于0,表示已经被压缩的数据大小
  return (iTiffCount > 0);
}

 

posted @ 2015-08-03 16:11  chencesc  阅读(644)  评论(0编辑  收藏  举报