110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//work();
}
void work()
{
while (true)
{
backgroundWorker1.RunWorkerAsync();
//backgroundWorker1.ReportProgress
}
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private Bitmap curBitmap = new Bitmap(600, 800);
private void Form1_Load(object sender, EventArgs e)
{
Image image = curBitmap;
Graphics graphics = Graphics.FromImage(image);
pictureBox1.Image = image;
float size = Convert.ToSingle(0.5);
Pen pen = new Pen(Color.Black, size);
int row = 600;
int col = 800;
for (int i = 0; i < row; i++)
{
graphics.DrawLine(pen, 0, 0 + 5 * i, 600, 0 + 5 * i);
}
for (int j = 0; j < col; j++)
{
graphics.DrawLine(pen, 0 + 5 * j, 0, 0 + 5 * j, 800);
}
}
private void button1_Click(object sender, EventArgs e)
{
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
curBitmap.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes =bmpData.Stride * curBitmap.Height;
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
//得到横向和纵向的缩放量
double x = 5;
double y = 5;
//图像的几何中心
int halfWidth = (int)(curBitmap.Width / 2);
int halfHeight = (int)(curBitmap.Height / 2);
int xz = 0;
int yz = 0;
int tempWidth = 0;
int tempHeight = 0;
byte[] tempArray = new byte[bytes];
//最临近插值法
for (int i = 0; i < curBitmap.Width; i++)
{
for (int j = 0; j < curBitmap.Height; j++)
{
//以图像的几何中心为坐标原点进行坐标转换
//按逆向映射法得到输入图像的坐标
tempHeight = i - halfHeight;
tempWidth = j - halfWidth;
//在不同的象限进行四舍五入处理
if (tempWidth > 0)
{
xz = (int)(tempWidth / x + 0.5);
}
else
{
xz = (int)(tempWidth / x - 0.5);
}
if (tempHeight > 0)
{
yz = (int)(tempHeight / y + 0.5);
}
else
{
yz = (int)(tempHeight / y - 0.5);
}
//坐标逆变换
tempWidth = xz + halfWidth;
tempHeight = yz + halfHeight;
//得到输出图像像素值
if (tempWidth < 0 || tempWidth >= curBitmap.Width || tempHeight < 0 || tempHeight >= curBitmap.Height)
{
//缩放后留下的空白部分用白色像素代替
tempArray[i * curBitmap.Width + j] = 255;
}
else
{
tempArray[i * curBitmap.Width + j] = grayValues[tempHeight * curBitmap.Width + tempWidth];
}
}
}
curBitmap.UnlockBits(bmpData);
}
}
}
int bytes = bmpData.Stride*curBitmap.Height;
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr,grayValues,0,bytes);